Reputation: 37
Sorry I am a noob at java, but how do i Initialize the variable petList without setting it equal to null?
for (int x = 0;x<= buttonPressed;x++){
println("adding box");
String[] petStrings = { "Withdraw", "Deposit", "Blah", };
//Create the combo box, select item at index 4.
@SuppressWarnings({ "rawtypes", "unchecked" })
JComboBox petList[] = null;// = new JComboBox(petStrings);
petList[x] = new JComboBox(petStrings);
petList[x].setSelectedIndex(1);
petList[x].setBounds(119, (buttonPressed *20)+15, 261, 23);
contentPane.add(petList[x]);
}
Upvotes: 1
Views: 13177
Reputation: 5055
Three things you must consider with creating arrays:
JComboBox [] petList;
petList = new JComboBox[someSize];
petList[i] = new JComboBox();
So, take the petList
outside the for-loop
(maybe defining it as an instance variable will be better):
public class YourClass{
//instance variables
private JComboBox[] petList; // you just declared an array of petList
private static final int PET_SIZE = 4;// assuming
//Constructor
public YourClass(){
petList = new JComboBox[PET_SIZE]; // here you initialed it
for(int i = 0 ; i < petList.length; i++){
//.......
petList[i] = new JComboBox(); // here you assigned each index to avoid `NullPointerException`
//........
}
}}
NOTE: this is not a compiled code, the will only demonstrates your solving your problem.
Upvotes: 3
Reputation: 41281
You need to loop. This will incur other errors such as bounds overlapping, but this should be the gist:
JComboBox[] petList = new JComboBox[petStrings.length];
for(int i=0; i<petStrings.length; i++){
petList[i]=new JComboBox(petStrings[i]);
}
Upvotes: 2