gpt4 book ai didi

java - 初始化 JComboBox[] 数组

转载 作者:行者123 更新时间:2023-11-29 07:55:32 24 4
gpt4 key购买 nike

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

最佳答案

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

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

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

关于java - 初始化 JComboBox[] 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18027626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com