java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 show 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 com.javacoderanch.example.swing;

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

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

    private void initialize() {

        setSize(300, 300);
        setDefaultCloseOperation(JFrame.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 comboBox = new JComboBox(months);

        //
        // By default combo box will only shows eight items in the drop down. When
        // more that 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);
    }

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