Set the Number of Visible Items in the Menu of a JComboBox Component in Java

Description

The following code shows how to set the Number of Visible Items in the Menu of a JComboBox Component.

Example


//  ww w .ja v a2 s. c om
import java.awt.BorderLayout;

import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] argv) throws Exception {
    JFrame frame = new JFrame("Selecting JComboBox");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    String[] items = new String[50];
    for (int i = 0; i < items.length; i++) {
      items[i] = "" + Math.random();
    }
    JComboBox cb = new JComboBox(items);

    // Retrieve the current max visible rows
    int maxVisibleRows = cb.getMaximumRowCount();

    // Change the current max visible rows
    maxVisibleRows = 20;
    cb.setMaximumRowCount(maxVisibleRows);
    
 
    
    frame.add(cb, BorderLayout.SOUTH);

    frame.setSize(400, 200);
    frame.setVisible(true);
  }
}

The code above generates the following result.

Set the Number of Visible Items in the Menu of a JComboBox Component in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer