Java 初始化 JComboBox[] 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18027626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:52:41  来源:igfitidea点击:

Initializing a JComboBox[] array

javaarraysswingjcombobox

提问by PadlockCode

Sorry I am a noob at java, but how do i Initialize the variable petList without setting it equal to null?

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

采纳答案by Azad

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

So, take the petListoutside the for-loop(maybe defining it as an instance variable will be better):

所以,把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`
 //........
 }
}}

NOTE: this is not a compiled code, the will only demonstrates your solving your problem.

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

回答by nanofarad

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