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.example.swing;

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

public class ComboBoxGetItems extends JFrame {
    public ComboBoxGetItems() {

    private void initialize() {
        setSize(300, 300);
        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);

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

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent 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++) {
                    if (i < count - 1) {
                        builder.append(", ");
                label.setText("Item count: " + count + "; ["
                    + builder.toString() + "]");


    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ComboBoxGetItems().setVisible(true);

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳

Leave a Reply

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