JComboBox Selection Change Listener? JComboBox Selection Change Listener? java java

JComboBox Selection Change Listener?


It should respond to ActionListeners, like this:

combo.addActionListener (new ActionListener () {    public void actionPerformed(ActionEvent e) {        doSomething();    }});

@John Calsbeek rightly points out that addItemListener() will work, too. You may get 2 ItemEvents, though, one for the deselection of the previously selected item, and another for the selection of the new item. Just don't use both event types!


Code example of ItemListener implementation

class ItemChangeListener implements ItemListener{    @Override    public void itemStateChanged(ItemEvent event) {       if (event.getStateChange() == ItemEvent.SELECTED) {          Object item = event.getItem();          // do something with object       }    }       }

Now we will get only selected item.

Then just add listener to your JComboBox

addItemListener(new ItemChangeListener());


I would try the itemStateChanged() method of the ItemListener interface if jodonnell's solution fails.