How do I listen for changes to the selected item in JComboBox?

This example demonstrates the ItemListener to listen for changes to the selected item in the JComboBox component.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.event.ItemEvent;
import java.awt.*;

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

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

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

        String[] items = new String[]{"A", "B", "C", "D", "E", "F"};
        JComboBox<String> comboBox = new JComboBox<>(items);

        final JTextArea textArea = new JTextArea(5, 15);
        textArea.setBorder(new BevelBorder(BevelBorder.LOWERED));

        // For listening to the changes of the selected items in the combo box
        // we need to add an ItemListener to the combo box component as shown
        // below.
        // Listening if a new items of the combo box has been selected.
        comboBox.addItemListener(event -> {
            // The item affected by the event.
            String item = (String) event.getItem();
            textArea.append("Affected items: " + item + "\n");
            if (event.getStateChange() == ItemEvent.SELECTED) {
                textArea.append(item + " selected\n");
            }
            if (event.getStateChange() == ItemEvent.DESELECTED) {
                textArea.append(item + " deselected\n");
            }
        });

        getContentPane().add(comboBox);
        getContentPane().add(textArea);
    }
}
Wayan

Leave a Reply

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