【发布时间】:2013-08-04 08:35:00
【问题描述】:
对不起,我是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]);
}
【问题讨论】:
-
先创建数组本身:
JComboBox petList[] = new JComboBox[sizeHere]; -
不相关:永远不要手动调整组件的大小/定位 - 这是 LayoutManager 的专属任务。
-
只是约定的一点,在声明数组时,最好将大括号放在声明的类型旁边而不是标识符之后。所以
JComboBox petList[];将是JComboBox[] petList;。其他人更容易这样阅读。 Donald Knuth 引用了相关的话; “让我们专注于向人类解释我们希望计算机做什么”
标签: java arrays swing jcombobox