初始化JComboBox []数组

时间:2013-08-02 23:29:31

标签: java arrays swing jcombobox

抱歉,我是java的菜鸟,但是如何初始化变量petList而不将其设置为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]);        
}

2 个答案:

答案 0 :(得分:3)

创建数组时必须考虑三件事:

  1. 声明:JComboBox [] petList;
  2. 初始化数组:petList = new JComboBox[someSize];
  3. 分配:petList[i] = new JComboBox();
  4. 所以,在petList之外取for-loop(可能将其定义为实例变量会更好):

    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`
     //........
     }
    }}
    

    注意:这不是编译代码,只会证明您解决问题。

答案 1 :(得分:2)

你需要循环。这将导致其他错误,例如边界重叠,但这应该是要点:

JComboBox[] petList = new JComboBox[petStrings.length];
for(int i=0; i<petStrings.length; i++){
    petList[i]=new JComboBox(petStrings[i]);
}