Reputation: 25
For my Java project I am creating buttons from strings stored in an array as such:
public class UserInterface implements ActionListener {
ArrayList<CardButton> currButtonList; // Current list of card buttons used
public void createAndShowGUI(String[] allCards){
//unrelated to question code
//for each String in allCards[]
for(int i=0; i<allCards.length; i++){
//Assign the button names relative to which card has is being created
String name = allCards[i];
CardButton button = new CardButton(name);
//add the button to the CardPanel
button.setFaceDown();
button.setBorderPainted(false);
int width = button.getWidth();
int height = button.getHeight();
button.setSize( new Dimension( width, height ) );
//button.setPreferredSize(new Dimension(150, 150));
CardPanel.add(button);
currButtonList.add(button);
}
}
//rest of creating the Panels, more unrelated to question code
Code complies but: Exception in thread "main" java.lang.NullPointerException at memory_game.GameFunction.(GameFunction.java:47) Which is where I try to assign listeners to each object in the array list. Am I correct in assuming that the ArrayList is not having the buttons added to it correctly? If so, why? How can I make this work?
Upvotes: 1
Views: 201
Reputation: 2496
Your arrayList is not initialized, default is NULL. That is why you get null pointer exception when you try to add button to currentButtonList variable.
Initialize your array with empty list as below.
ArrayList<CardButton> currButtonList = new ArrayList<CardButton>(); // Current list of card buttons used
Upvotes: 1
Reputation: 144
Are you ever instantiating your ArrayList like
ArrayList<CardButton> currButtonList = new ArrayList<CardButton>();
I don't believe ArrayList is an intrinsic type that will work without instantiating it.
Upvotes: 1
Reputation: 201497
You need to instantiate your ArrayList<CardButton>
. This is wrong (because it leaves currButtonList
undefined, that is null) -
ArrayList<CardButton> currButtonList; // Current list of card buttons used
Try this instead
// Current list of card buttons used
List<CardButton> currButtonList = new ArrayList<CardButton>();
Or you could add this to your UserInterface constructor(s) -
currButtonList = new ArrayList<CardButton>(); // Instantiate the currButtonList.
Finally, as for your subject line question - you seem to be doing that correctly with these lines -
CardButton button = new CardButton(name); // Create a new CardButton instance.
currButtonList.add(button); // Add it to the list (currButtonList was null, not button)
Upvotes: 3