Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a switch statement for a JComboBox

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?

like image 875
Ricky Avatar asked Dec 02 '25 09:12

Ricky


2 Answers

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;
            }
        }
    });
like image 93
Bon Avatar answered Dec 05 '25 16:12

Bon


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.

like image 42
Blip Avatar answered Dec 05 '25 17:12

Blip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!