Using JComboBox in Java Swing tutorial

JComboBox is a Swing component in Java that allows users to select an option from a dropdown list.

It can be used for various purposes, such as selecting items from a list, filtering options, or providing a compact way to present a selection of items.

Users can also type in custom values if the combo box is editable.

In this tutorial, we will explore:

1. Creating a Basic JComboBox

The simplest way to create a combo box is by using the JComboBox constructor, which takes an array or a vector of items as its argument.

Example 1: Basic JComboBox

import javax.swing.*;

public class JComboBoxExample1 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Basic JComboBox Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 150);

            // Create an array of items for the combo box
            String[] items = {"Apple", "Banana", "Orange", "Grapes"};

            // Create a JComboBox with the items
            JComboBox comboBox = new JComboBox<>(items);

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(comboBox);

            frame.setVisible(true);
        });
    }
}

Explanation:

The combo box is created with a list of items (“Apple”, “Banana”, “Orange”, and “Grapes”).
The combo box is added to the JFrame and displayed, allowing users to select one of the items from the dropdown list.

2. Handling Item Selection Events

You can listen for item selection events in the combo box using an ActionListener. This allows you to perform actions when the user selects a different item.

Example 2: Handling Item Selection

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

public class JComboBoxExample2 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Item Selection Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 150);

            String[] items = {"Red", "Green", "Blue", "Yellow"};
            JComboBox comboBox = new JComboBox<>(items);

            JLabel label = new JLabel("Selected Color: Red");

            // Add an ActionListener to handle item selection
            comboBox.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // Get the selected item
                    String selectedItem = (String) comboBox.getSelectedItem();
                    label.setText("Selected Color: " + selectedItem);
                }
            });

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(comboBox);
            frame.add(label);

            frame.setVisible(true);
        });
    }
}

Explanation:

We add an ActionListener to the combo box, which listens for changes in the selected item.
When the user selects an item from the combo box, the actionPerformed() method is called, and the selected item is retrieved using getSelectedItem().
The label is updated to display the currently selected item.

3. Making the Combo Box Editable

By default, JComboBox is not editable, meaning users can only select from the predefined options. However, you can make the combo box editable, allowing users to enter custom values.

Example 3: Editable JComboBox

import javax.swing.*;

public class JComboBoxExample3 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Editable JComboBox Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 150);

            String[] items = {"Red", "Green", "Blue", "Yellow"};
            JComboBox comboBox = new JComboBox<>(items);

            // Make the combo box editable
            comboBox.setEditable(true);

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(comboBox);

            frame.setVisible(true);
        });
    }
}

Explanation:

We call the setEditable(true) method on the combo box to allow users to enter their own custom values.
The combo box remains functional with predefined items, but users can also type in new values.

4. Adding and Removing Items Dynamically

You can add and remove items from the combo box dynamically at runtime using the addItem() and removeItem() methods.

Example 4: Adding and Removing Items Dynamically

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

public class JComboBoxExample4 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Add/Remove Items Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 200);

            JComboBox comboBox = new JComboBox<>();
            comboBox.addItem("Apple");
            comboBox.addItem("Banana");

            JTextField newItemField = new JTextField(10);
            JButton addButton = new JButton("Add Item");
            JButton removeButton = new JButton("Remove Selected");

            // Add an item to the combo box when the button is clicked
            addButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String newItem = newItemField.getText();
                    if (!newItem.isEmpty()) {
                        comboBox.addItem(newItem); // Add the new item
                        newItemField.setText(""); // Clear the input field
                    }
                }
            });

            // Remove the selected item from the combo box
            removeButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String selectedItem = (String) comboBox.getSelectedItem();
                    if (selectedItem != null) {
                        comboBox.removeItem(selectedItem); // Remove the selected item
                    }
                }
            });

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(comboBox);
            frame.add(newItemField);
            frame.add(addButton);
            frame.add(removeButton);

            frame.setVisible(true);
        });
    }
}

Explanation:

We dynamically add items to the combo box using the addItem() method when the “Add Item” button is clicked.
The selected item is removed using the removeItem() method when the “Remove Selected” button is clicked.

5. Customizing the Appearance of JComboBox

You can customize the appearance of the combo box by modifying its font, background, and foreground (text color).

Example 5: Customizing JComboBox Appearance

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

public class JComboBoxExample5 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Custom JComboBox Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 150);

            String[] items = {"Apple", "Banana", "Orange", "Grapes"};
            JComboBox comboBox = new JComboBox<>(items);

            // Customize the appearance of the combo box
            comboBox.setFont(new Font("Serif", Font.BOLD, 16));
            comboBox.setForeground(Color.BLUE);
            comboBox.setBackground(Color.LIGHT_GRAY);

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(comboBox);

            frame.setVisible(true);
        });
    }
}

Explanation:

We customize the font, text color, and background color of the combo box using setFont(), setForeground(), and setBackground().

6. Working with Custom Objects in JComboBox

You can store and display custom objects in JComboBox. The toString() method of the object is used to display the item in the combo box, but you can still retrieve the full object.

Example 6: Using Custom Objects in JComboBox

import javax.swing.*;

class Item {
    private String name;
    private int id;

    public Item(String name, int id) {
        this.name = name;
        this.id = id;
    }

    @Override
    public String toString() {
        return name;
    }

    public int getId() {
        return id;
    }
}

public class JComboBoxExample6 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Custom Object JComboBox Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 150);

            // Create custom objects to store in the JComboBox
            Item[] items = {
                new Item("Apple", 1),
                new Item("Banana", 2),
                new Item("Orange", 3),
                new Item("Grapes", 4)
            };

            JComboBox comboBox = new JComboBox<>(items);
            JLabel label = new JLabel("Selected Item ID: 1");

            // Add an ActionListener to handle item selection
            comboBox.addActionListener(e -> {
                Item selectedItem = (Item) comboBox.getSelectedItem();
                if (selectedItem != null) {
                    label.setText("Selected Item ID: " + selectedItem.getId());
                }
            });

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(comboBox);
            frame.add(label);

            frame.setVisible(true);
        });
    }
}

Explanation:

We create a custom Item class with a name and an ID. The toString() method is overridden to display the item name in the combo box.
When the user selects an item, the corresponding ID is displayed in the label by retrieving the full object from the combo box.

Conclusion

JComboBox is a versatile and easy-to-use Swing component for selecting items from a list. You can create a basic combo box with a set of predefined items, handle item selection events, make it editable, and dynamically add or remove items. Additionally, you can customize its appearance and even store custom objects within the combo box.

Summary of Key Points:

Basic JComboBox: Use new JComboBox<>(items) to create a combo box with a set of items.
Handling Events: Use addActionListener() to listen for item selection and respond to changes.
Editable ComboBox: Make the combo box editable using setEditable(true).
Add/Remove Items: Add items dynamically using addItem() and remove items using removeItem().
Custom Appearance: Customize the font, foreground (text color), and background color using setFont(), setForeground(), and setBackground().
Custom Objects: Store custom objects in the combo box, and retrieve them using getSelectedItem(). The toString() method is used to display the items.

Related posts

Tutorial on Java GroupLayout in Swing

Tutorial on Java GridBagLayout in Swing

Tutorial on Java GridLayout in Swing