I have a JComboBox set up as shown below:
private String[] boxChoices = {"option 1", "option 2"};
JcomboBox box = new JCombobox(boxChoices);
box.addItemListener()
{
public void itemStateChanged(ItemEvent event)
{
int selection = box.getSelectedIndex();
switch (selection)
{
case 0: JOptionPane.showMessageDialog(null, "you have selected option 1");
break;
case 1: JOptionPane.showMessageDialog(null, "you have selected option 2");
break;
default: break;
}
}
}
My issue is that when I pick an option the message will be shown twice instead of once. For example if I choose Option 1 the following would appear:
you have selected option 1
you have selected option 1
What is causing this to happen?
In addition to @Blip's answer, you can also use actionListener. An actionEvent for JComboBox is only triggered once when you change a selection.
box.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
int selection = box.getSelectedIndex();
switch (selection) {
case 0:
JOptionPane.showMessageDialog(null, "you have selected option 1");
break;
case 1:
JOptionPane.showMessageDialog(null, "you have selected option 2");
break;
default:
break;
}
}
});
This behaviour occurs because Item listener is called 2 times because of selection of any item in the JComboBox. The first is called for deselection of previously selected item and the second time it is called for selection of the new item.
You can filter this by using a if clause to reflect the actual event you want to catch i.e. Selection or deselection :
if(event.getStateChange() == ItemEvent.SELECTED)
OR
if(event.getStateChange() == ItemEvent.DESELECTED)
based on your preference of choice of state change you want to trap.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With