不应发生的NullPointerException

时间:2013-07-18 03:12:44

标签: java nullpointerexception

我很遗憾地发布,以防万一我只是做了一些愚蠢的事情,但我希望有一些奇怪的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)

2 个答案:

答案 0 :(得分:5)

ShopJInternalFrame.shopHolderWAIType = new JLabel[itemSoldCount];

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

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

shopHolderWAIType[k]为空。

答案 1 :(得分:0)

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

ShopJInternalFrame.shopHolderWAIType[k] = new new JLabel();