1

抱歉,我是 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]);        
}
4

2 回答 2

3

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

  1. 宣言: JComboBox [] petList;
  2. 初始化数组:petList = new JComboBox[someSize];
  3. 分配: 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`
 //........
 }
}}

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

于 2013-08-02T23:40:36.643 回答
2

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

JComboBox[] petList = new JComboBox[petStrings.length];
for(int i=0; i<petStrings.length; i++){
    petList[i]=new JComboBox(petStrings[i]);
}
于 2013-08-02T23:31:32.017 回答