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

Leave a Reply

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