tags:

views:

10121

answers:

4

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 the answer is good. Commence the vote down. :)

+6  A: 

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!

jodonnell
I'd prefer ItemListener (just make sure to check the ItemEvent to see whether it is a selection or deselection even). The ActionListener can be fired even if the selection hasn't changed (i.e. if the user clicks on the already selected item). This may or may not be what you want.
Dan Dyer
+2  A: 

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

John Calsbeek
A: 

how would you pass the selected item on the combo box into the do somthing method?

You should ask this as a question instead of an answer here.
Jay R.
A: 

int selectedIndex = myComboBox.getSelectedIndex();

-or-

Object selectedObject = myComboBox.getSelectedValue();

-or-

String selectedValue = myComboBox.getSelectedValue().toString();

JavaKeith