Jamie Keeling
Jamie Keeling

Reputation: 9966

Performing action on JComboBox - SwingUI

I've implemented a ComboBox using NetBeans that has a list of values, I want to be able to perform an action whenever the selected index has changed. An example being when a user changes the current item from Item 1 to Item 2.

Upvotes: 1

Views: 2911

Answers (1)

mre
mre

Reputation: 44240

Here's a usage example from The Java Tutorials:

public class ComboBoxDemo ... implements ActionListener {
    . . .
        petList.addActionListener(this) {
    . . .
    public void actionPerformed(ActionEvent e) {
        JComboBox cb = (JComboBox)e.getSource();
        String petName = (String)cb.getSelectedItem();
        updateLabel(petName);
    }
    . . .
}

Edit:

An ActionListener is

The listener interface for receiving action events. The class that is interested in processing an action event implements this interface, and the object created with that class is registered with a component, using the component's addActionListener method. When the action event occurs, that object's actionPerformed method is invoked.

Edit 2:

Here's another usage example to satisfy kleopatra, that is, one that is more exemplary of best practices:

JComboBox yourComboBox = new JComboBox();
yourComboBox.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // do stuff
    }
});

Upvotes: 3

Related Questions