How do I change the number of visible items in JComboBox?

In this example you’ll see how we can change the default number of visible items in the combo box. By default, it only shows eight items at once and when the combo box has more items a scrollbar will be shown, so we can scroll up and down in the combo box list.

If we want to change this value we can call the setMaximumRowCount(int count) of the JComboBox. Let’s see the following example for more details.

package org.kodejava.swing;

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

public class ComboBoxMaximumRows extends JFrame {
    public ComboBoxMaximumRows() {
        initialize();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new ComboBoxMaximumRows().setVisible(true));
    }

    private void initialize() {
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        // Create some items for our JComboBox component. In this example we are
        // going to pass an array of string which are the name of the month.
        String[] months = {"January", "February", "March", "April", "Mei", "June",
                "July", "August", "September", "October", "November", "December"};

        // Create a month selection combo box.
        JComboBox<String> comboBox = new JComboBox<>(months);

        // By default, combo box will only show eight items in the drop-down. When
        // more than eight items are in the combo box a default scrollbar will be
        // shown. If we want to display more items we can change it by calling the
        // setMaximumRowCount() method.
        comboBox.setMaximumRowCount(12);

        getContentPane().add(comboBox);
    }
}

1 Comments

Leave a Reply to siraj Cancel reply

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