How do I create a drop-down list using JComboBox in Java Swing?

Use JComboBox to let the user choose one item from a drop-down list. In this example, selecting a programming language updates a label below the list.

Source code

Save the following code as ComboBoxExample.java:

import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class ComboBoxExample {
    void main() {
        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        String[] languages = {"Java", "Python", "Kotlin"};
        JComboBox<String> languageBox = new JComboBox<>(languages);

        JLabel prompt = new JLabel("Choose a language:");
        prompt.setLabelFor(languageBox);

        JLabel selection = new JLabel(
                "Selected: " + languageBox.getSelectedItem(),
                SwingConstants.CENTER);

        languageBox.addActionListener(event ->
                selection.setText(
                        "Selected: " + languageBox.getSelectedItem()));

        JPanel controls = new JPanel();
        controls.add(prompt);
        controls.add(languageBox);

        JPanel content = new JPanel(new BorderLayout(0, 10));
        content.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
        content.add(controls, BorderLayout.PAGE_START);
        content.add(selection, BorderLayout.CENTER);

        JFrame frame = new JFrame("Language Picker");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What the window looks like

Illustration of the Language Picker window with Python selected and the label Selected: Python below it

Explanation

new JComboBox<>(languages) creates a drop-down list from the array. The first item, Java, is selected when the window opens. The list is non-editable by default, so the user chooses from the supplied options.

Use getSelectedItem() to read the current selection. It returns an Object, which you can concatenate directly with a label such as "Selected: ". If there is no selection, it returns null. This example always starts with a selection and offers no way to clear it.

addActionListener() registers code that Swing calls when the user makes a selection. The listener reads the current item and updates the existing label with setText().

Run the example

javac ComboBoxExample.java
java ComboBoxExample

The window opens with Selected: Java. Choose Python from the drop-down list, and the label changes to Selected: Python.

Wayan

Leave a Comment

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