2013-07-18 32 views
0

對不起,我只是在做一些愚蠢的事情,但我希望有一些怪異的Java事件引起這種我不知道的東西,並且可以幫助其他人。我在這裏忽略了什麼嗎?爲什麼是NPE?不應該發生的NullPointerException

這是我的代碼:

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) 

回答

5
ShopJInternalFrame.shopHolderWAIType = new JLabel[itemSoldCount]; 

此分配用於陣列存儲,但不用於任何JLabel對象。該數組包含此時的所有空值。當您到達時

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

shopHolderWAIType[k]爲空。

+0

咄多麼愚蠢的問題,對不起了睡覺時間。謝謝您的幫助! – KisnardOnline

+1

在某些時候發生在每個人身上:-) –

0

ShopJInternalFrame.shopHolderWAIType[k]將爲空,因爲您尚未爲單個陣列成員分配任何內存。所以你需要在使用數組成員之前做到這一點。

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