How do I add an action listener to JComboBox?

The code below shows you how to add an ActionListener to a JComboBox component. In the snippet we add a listener by calling the addActionListener() method and give an instance of ActionListener listener as an anonymous class (a class without a specified name) as the parameter.

The ActionListener interface contract said that we must implement the actionPerformed(ActionEvent e) method. This is the place where the event will be handled by our program.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.FlowLayout;

public class ComboBoxActionListener extends JFrame {
    public ComboBoxActionListener() {
        initialize();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new ComboBoxActionListener().setVisible(true));
    }

    private void initialize() {
        setSize(300, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        String[] names = new String[]{
                "John", "Paul", "George", "Ringo"
        };
        JComboBox<String> comboBox = new JComboBox<>(names);
        comboBox.setEditable(true);

        // Create an ActionListener for the JComboBox component.
        comboBox.addActionListener(event -> {
            // Get the source of the component, which is our combo
            // box.
            JComboBox comboBox1 = (JComboBox) event.getSource();

            // Print the selected items and the action command.
            Object selected = comboBox1.getSelectedItem();
            System.out.println("Selected Item  = " + selected);
            String command = event.getActionCommand();
            System.out.println("Action Command = " + command);

            // Detect whether the action command is "comboBoxEdited"
            // or "comboBoxChanged"
            if ("comboBoxEdited".equals(command)) {
                System.out.println("User has typed a string in " +
                        "the combo box.");
            } else if ("comboBoxChanged".equals(command)) {
                System.out.println("User has selected an item " +
                        "from the combo box.");
            }
        });
        getContentPane().add(comboBox);
    }
}
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.