I'm trying to get an event to fire whenever a choice is made from a JComboBox
.
The problem I'm having is that there is no obvious addSelectionListener()
method.
I've tried to use actionPerformed()
, but it never fires.
Short of overriding the model for the JComboBox
, I'm out of ideas.
How do I get notified of a selection change on a JComboBox
?**
Edit: I have to apologize. It turns out I was using a misbehaving subclass of JComboBox
, but I'll leave the question up since your answer is good.
It should respond to ActionListeners, like this:
@John Calsbeek rightly points out that
addItemListener()
will work, too. You may get 2ItemEvents
, 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
implementationNow we will get only selected item.
Then just add listener to your JComboBox
I would try the
itemStateChanged()
method of theItemListener
interface if jodonnell's solution fails.Here is creating a ComboBox adding a listener for item selection change:
You may try these
-or-
-or-
I was recently looking for this very same solution and managed to find a simple one without assigning specific variables for the last selected item and the new selected item. And this question, although very helpful, didn't provide the solution I needed. This solved my problem, I hope it solves yours and others. Thanks.
How do I get the previous or last item?