Reputation: 23
I'm stuck on making two dropdown menus in Java GUI Form that the selection of first one will determine the choices in the second menu.
What I hope to achieve looks like this: enter image description here
And after I switched my choice in comboBox1, it looks like this: enter image description here
Here's my tester code:
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);
});
}
But I always run into NullPointerException at removeAllItems() and comboBox2.getSelectedItems() everytime I try to switch my choice in comboBox1.
I tried to debug it, but it seems it's because actionListener of comboBox2 was called whenever the program did removeAllItems() and comboBox2.addItem(). And I don't know how to handle this
A little help?
Upvotes: 2
Views: 24
Reputation: 285405
You are right that removing all items from the JComboBox causes its ActionListener to fire and to return selection of null.
Possible solutions:
toString()
on the item returned (that's what throws the NPE -- calling toString()
on a null reference) but rather cast the selected item returned as a String. A cast won't throw the NPE.Example of the first:
ActionListener[] actionListeners = tester.comboBox2.getActionListeners();
for (ActionListener actionListener : actionListeners) {
tester.comboBox2.removeActionListener(actionListener);
}
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);
}
}
for (ActionListener actionListener : actionListeners) {
tester.comboBox2.addActionListener(actionListener);
}
Example of the second:
String colorChoice = (String) tester.comboBox2.getSelectedItem();
String flowerChoice = (String) tester.comboBox1.getSelectedItem();
System.out.println(colorChoice + " " + flowerChoice);
Upvotes: 1