java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to add an action listener to JComboBox?

The code below shows you how to add an ActionListener to a JComboBox component.

package com.javacoderanch.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

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

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

        String[] names = new String[] {"James", "Joshua", "Matt", "John", "Paul"};
        JComboBox comboBox = new JComboBox(names);
        comboBox.setEditable(true);

        //
        // Create an ActionListener for the JComboBox component.
        //
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                //
                // Get the source of the component, which is our combo box.
                //
                JComboBox comboBox = (JComboBox) event.getSource();

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

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

        getContentPane().add(comboBox);
    }

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