gpt4 book ai didi

java - 不应该发生的 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 17:22:19 24 4
gpt4 key购买 nike

我很抱歉地发帖,以防万一这只是我正在做的愚蠢的事情,但我希望有一些我不知道的奇怪的 Java 事情导致了这一点,这可以帮助其他人。我在这里忽略了什么吗?为什么是 NPE?

这是我的代码:

SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
int itemSoldCount = Integer.parseInt(afterAt[1]);
System.out.println("itemSoldCount: " + itemSoldCount);
ShopJInternalFrame.shopHolderWAIType = new JLabel[itemSoldCount];

int i = 2;
for (int k = 0; k < itemSoldCount; k++){
String waiType = afterAt[i];
System.out.println("ShopJInternalFrame.shopHolderWAIType.length: " + ShopJInternalFrame.shopHolderWAIType.length);
System.out.println("waiType: " + waiType);
System.out.println("k: " + k);
ShopJInternalFrame.shopHolderWAIType[k].setText(waiType); //line 530

这是我的输出:

itemSoldCount: 2
ShopJInternalFrame.shopHolderWAIType.length: 2
waiType: A
k: 0
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.jayavon.game.client.MyCommandReceiver$8.run(MyCommandReceiver.java:530)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

最佳答案

ShopJInternalFrame.shopHolderWAIType = new JLabel[itemSoldCount];

这会为数组分配存储空间,但不会为任何JLabel分配存储空间。对象。此时数组包含所有空值。当你到达

ShopJInternalFrame.shopHolderWAIType[k].setText(waiType);

shopHolderWAIType[k]为空。

关于java - 不应该发生的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17713881/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com