Reputation: 740
I am sorry to post that in case it is just something stupid I am doing, but I hope there is some weird Java thing causing this that I am unaware of and can that will help others. Am I overlooking something here? Why the NPE?
Here is my code:
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
Here is my output:
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)
Upvotes: 0
Views: 81
Reputation: 839
ShopJInternalFrame.shopHolderWAIType[k]
will be null because you have not allocated any memory for individual array member. So you need to do this before you use the array member.
ShopJInternalFrame.shopHolderWAIType[k] = new new JLabel();
Upvotes: 0
Reputation: 86744
ShopJInternalFrame.shopHolderWAIType = new JLabel[itemSoldCount];
This allocates storage for the array, but not for any JLabel
objects. The array contains all nulls at this point. When you reach
ShopJInternalFrame.shopHolderWAIType[k].setText(waiType);
shopHolderWAIType[k]
is null.
Upvotes: 5