【发布时间】:2016-12-04 03:36:50
【问题描述】:
我坚持在 Java GUI 表单中制作两个下拉菜单,第一个的选择将决定第二个菜单中的选择。
我希望达到的效果如下所示: enter image description here
当我在 comboBox1 中切换选择后,它看起来像这样: enter image description here
这是我的测试代码:
public static void main(String[] args) {
Tester tester = new Tester();
String[] flower = {"Rose", "Tulip"};
String[] color1 = {"Yellow", "Blue", "Red"};
String[] color2 = {"Purple", "White", "Green"};
for (String flowerPicked : flower) {
tester.comboBox1.addItem(flowerPicked);
}
tester.comboBox1.addActionListener(e -> {
// remove previous items in comboBox2 everytime a new item in box1 is selcted
tester.comboBox2.removeAllItems();
String flowerChoice = tester.comboBox1.getSelectedItem().toString();
if (flowerChoice.equalsIgnoreCase("Rose"))
for (String colorPicked : color1) {
tester.comboBox2.addItem(colorPicked );
}
else
for (String type : color2) {
tester.comboBox2.addItem(type);
}
});
tester.comboBox2.addActionListener(e -> {
String colorChoice = tester.comboBox2.getSelectedItem().toString();
String flowerChoice = tester.comboBox1.getSelectedItem().toString();
system.out.println(colorChoice + " " + flowerChoice);
});
}
但是每次我尝试在comboBox1中切换我的选择时,我总是在removeAllItems()和comboBox2.getSelectedItems()处遇到NullPointerException。
我尝试调试它,但似乎是因为每当程序执行 removeAllItems() 和 comboBox2.addItem() 时都会调用 comboBox2 的 actionListener。我不知道如何处理这个
有点帮助?
【问题讨论】:
标签: java swing user-interface actionlistener jcombobox