抱歉,我是Java的菜鸟,但是如何在不将其设置为null的情况下初始化变量petList?

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]);
}

最佳答案

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


声明:JComboBox [] petList;
初始化数组:petList = new JComboBox[someSize];
分配:petList[i] = new JComboBox();


因此,将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`
 //........
 }
}}


注意:这不是已编译的代码,只会显示您解决问题的方式。

10-08 10:54