How do I determine if the menu of JComboBox is displayed?

This example show how to create an implementation of PopupMenuListener for listening to when the JComboBox menu is visible, invisible or cancelled.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.event.PopupMenuListener;
import javax.swing.event.PopupMenuEvent;
import java.awt.*;

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

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

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

        Integer[] years = new Integer[]{
                2016, 2017, 2018, 2019, 2020,
                2021, 2022, 2023, 2024, 2025
        };

        JComboBox<Integer> comboBox = new JComboBox<>(years);
        comboBox.setEditable(true);

        // Adds a PopupMenu listener which will listen to notification
        // messages from the popup portion of the combo box.
        comboBox.addPopupMenuListener(new PopupMenuListener() {
            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                // This method is called before the popup menu becomes visible.
                System.out.println("PopupMenuWillBecomeVisible");
            }

            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                // This method is called before the popup menu becomes invisible
                System.out.println("PopupMenuWillBecomeInvisible");
            }

            public void popupMenuCanceled(PopupMenuEvent e) {
                // This method is called when the popup menu is canceled
                System.out.println("PopupMenuCanceled");
            }
        });

        getContentPane().add(comboBox);
    }
}

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);
    }
}

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);
    }
}

How do I change the number of visible items in JComboBox?

In this example you’ll see how we can change the default number of visible items in the combo box. By default, it only shows eight items at once and when the combo box has more items a scrollbar will be shown, so we can scroll up and down in the combo box list.

If we want to change this value we can call the setMaximumRowCount(int count) of the JComboBox. Let’s see the following example for more details.

package org.kodejava.swing;

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

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

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

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

        // Create some items for our JComboBox component. In this example we are
        // going to pass an array of string which are the name of the month.
        String[] months = {"January", "February", "March", "April", "Mei", "June",
                "July", "August", "September", "October", "November", "December"};

        // Create a month selection combo box.
        JComboBox<String> comboBox = new JComboBox<>(months);

        // By default, combo box will only show eight items in the drop-down. When
        // more than eight items are in the combo box a default scrollbar will be
        // shown. If we want to display more items we can change it by calling the
        // setMaximumRowCount() method.
        comboBox.setMaximumRowCount(12);

        getContentPane().add(comboBox);
    }
}

How do I add items and remove items from JComboBox?

This example demonstrate how to add an items into a specific position in the combo box list or at the end of the list using the insertItemAt(Object o, int index) and addItem(Object o) method. In the code we also learn how to remove one or all items from the list using removeItemAt(int index) method and removeAllItems() method of JComboBox.

package org.kodejava.swing;

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

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

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

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

        String[] items = new String[]{"Two", "Four", "Six", "Eight"};
        final JComboBox<String> comboBox = new JComboBox<>(items);

        getContentPane().add(comboBox);

        JButton button1 = new JButton("Add One");
        button1.addActionListener(e -> {
            // Add item "One" at the beginning of the list.
            comboBox.insertItemAt("One", 0);
        });

        JButton button2 = new JButton("Add Five and Nine");
        button2.addActionListener(e -> {
            // Add item Five on the third index and Nine at the end of the
            // list.
            comboBox.insertItemAt("Five", 3);
            comboBox.addItem("Nine");
        });

        getContentPane().add(button1);
        getContentPane().add(button2);

        JButton remove1 = new JButton("Remove Eight and Last");
        remove1.addActionListener(e -> {
            // Remove the Eight item and the last item from the list.
            comboBox.removeItemAt(5);
            comboBox.removeItemAt(comboBox.getItemCount() - 1);
        });

        JButton remove2 = new JButton("Remove All");
        remove2.addActionListener(e -> comboBox.removeAllItems());

        getContentPane().add(remove1);
        getContentPane().add(remove2);
    }
}

How do I get items of JComboBox?

This example demonstrate the use of JComboBox‘s getItemCount() method and getItemAt(int index) to get the number of items inside the combo box and how to obtain each of them.

package org.kodejava.swing;

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

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

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

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

        // Create JComboBox with grade as the values;
        String[] items = new String[]{"A", "B", "C", "D", "E", "F"};
        final JComboBox<String> gradeCombo = new JComboBox<>(items);
        getContentPane().add(gradeCombo);

        JButton button = new JButton("Get Items");
        final JLabel label = new JLabel("Items count: ");

        button.addActionListener(e -> {
            // Get the number of items in the combo box drop-down. Iterate
            // from zero to the number of combo box items and get each item
            // of the specified index.
            //
            // In this example we just place the items inside a StringBuilder
            // and print it later on.
            int count = gradeCombo.getItemCount();
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < count; i++) {
                builder.append(gradeCombo.getItemAt(i));
                if (i < count - 1) {
                    builder.append(", ");
                }
            }
            label.setText("Item count: " + count + "; ["
                    + builder + "]");
        });

        getContentPane().add(button);
        getContentPane().add(label);
    }
}

How do I set and get the selected item in JComboBox?

The code below demonstrate how to set the selected item of JComboBox and then on how to get the value of the selected item. In this example we set the JComboBox component so that user can enter their own value.

package org.kodejava.swing;

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

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

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

    private void initialize() {
        setSize(500, 500);
        setTitle("JComboBox Selected Item");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        // Create a combo box with four items and set it to editable so that 
        // user can
        // enter their own value.
        final JComboBox<String> comboBox = 
                new JComboBox<>(new String[]{"One", "Two", "Three", "Four"});
        comboBox.setEditable(true);
        getContentPane().add(comboBox);

        // Create two button that will set the selected item of the combo box. 
        // The first button select "Two" and second button select "Four".
        JButton button1 = new JButton("Set Two");
        getContentPane().add(button1);
        button1.addActionListener(e -> comboBox.setSelectedItem("Two"));

        JButton button2 = new JButton("Set Four");
        getContentPane().add(button2);
        button2.addActionListener(e -> comboBox.setSelectedItem("Four"));

        // Create a text field for displaying the selected item when we press 
        // the "Get Value" button. When user enter their own value the selected 
        // item returned is the string that entered by user.
        final JTextField textField = new JTextField("");
        textField.setPreferredSize(new Dimension(150, 20));

        JButton button3 = new JButton("Get Value");
        getContentPane().add(button3);
        getContentPane().add(textField);
        button3.addActionListener(
                e -> textField.setText((String) comboBox.getSelectedItem()));
    }
}

How do I create JComboBox?

A JComboBox allows user to select a value from a drop-down items available in the component. When the combo box set to editable user can enter their own value by typing it directly in the combo box editor. The code below demonstrate how you can create a simple combo box component.

package org.kodejava.swing;

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

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

    private void initialize() {
        setSize(500, 500);
        setTitle("JComboBox Demo");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        JLabel label1 = new JLabel("Month  :");
        JLabel label2 = new JLabel("Number :");

        // Create some items for our JComboBox component. In this example we are
        // going to pass an array of string which are the name of the month.
        String[] months = {"January", "February", "March", "April", "Mei", "June",
                "July", "August", "September", "October", "November", "December"};

        // Create a month selection combo box.
        JComboBox<String> comboBox = new JComboBox<>(months);

        // Below, instead of passing directly a string array we create a ComboBoxModel
        // as the combo box data model. Using a model we can for example define the
        // selected item of the combo box.
        ComboBoxModel<String> model =
                new DefaultComboBoxModel<>(new String[]{"1", "2", "3", "4", "5"});
        model.setSelectedItem("3");
        JComboBox<String> numberComboBox = new JComboBox<>(model);

        // We also set the combo box to be editable so that user can enter their own
        // value other that those defined in the combo box.
        numberComboBox.setEditable(true);

        // Add the entire component to out frame content pane.
        getContentPane().add(label1);
        getContentPane().add(comboBox);

        getContentPane().add(label2);
        getContentPane().add(numberComboBox);
    }

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