PadlockCode
PadlockCode

Reputation: 37

Initializing a JComboBox[] array

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

Answers (2)

Azad
Azad

Reputation: 5055

Three things you must consider with creating arrays:

  1. Declaration: JComboBox [] petList;
  2. Initial the array: petList = new JComboBox[someSize];
  3. Assigning: 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

nanofarad
nanofarad

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

Related Questions