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

4 Comments

Leave a Reply

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