0

我很抱歉发布它,以防我正在做一些愚蠢的事情,但我希望有一些奇怪的 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)
4

2 回答 2

5
ShopJInternalFrame.shopHolderWAIType = new JLabel[itemSoldCount];

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

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

shopHolderWAIType[k]一片空白。

于 2013-07-18T03:14:35.010 回答
0

ShopJInternalFrame.shopHolderWAIType[k]将为空,因为您没有为单个数组成员分配任何内存。因此,您需要在使用数组成员之前执行此操作。

ShopJInternalFrame.shopHolderWAIType[k] = new new JLabel();
于 2013-07-18T03:19:05.683 回答