Java JComboBox setupComboBoxMaxRows( T inComboBox)

Here you can find the source of setupComboBoxMaxRows( T inComboBox)

Description

Set the maximum number of rows for a JComboBox so that it always can fit on the screen

License

Open Source License

Declaration

public static <T extends javax.swing.JComboBox> void setupComboBoxMaxRows(
        T inComboBox) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.basic.BasicComboPopup;

public class Main {
    /**/*  w w w.ja v  a2 s. c  o m*/
     * Set the maximum number of rows for a JComboBox so that
     * it always can fit on the screen
     */
    public static <T extends javax.swing.JComboBox> void setupComboBoxMaxRows(
            T inComboBox) {
        // find the max height of all popup items
        BasicComboPopup popup = (BasicComboPopup) inComboBox
                .getAccessibleContext().getAccessibleChild(0);
        JList list = popup.getList();
        ListModel lm = list.getModel();
        ListCellRenderer renderer = list.getCellRenderer();
        int maxItemHeight = 12; // pick some absolute minimum here
        for (int i = 0; i < lm.getSize(); ++i) {
            Object value = lm.getElementAt(i);
            Component c = renderer.getListCellRendererComponent(list,
                    value, i, false, false);
            maxItemHeight = Math.max(maxItemHeight,
                    c.getPreferredSize().height);
        }

        int itemsPerScreen = inComboBox.getItemCount();
        // calculate the number of items that will fit on the screen
        if (!GraphicsEnvironment.isHeadless()) {
            // note: this line returns the maximum available size, accounting all
            // taskbars etc. no matter where they are aligned:
            Rectangle maxWindowBounds = GraphicsEnvironment
                    .getLocalGraphicsEnvironment().getMaximumWindowBounds();
            itemsPerScreen = (int) maxWindowBounds.getHeight()
                    / maxItemHeight;
        }

        int c = Math.min(itemsPerScreen, inComboBox.getItemCount());
        inComboBox.setMaximumRowCount(c);
    }
}

Related

  1. setComboBoxTheme(JComboBox comboBox)
  2. setErrorBackground(JComboBox comp)
  3. setJComboBoxAsHeavyweight(JComboBox combo)
  4. setPopupComboChoices(JComboBox aComboBox, String aS)
  5. setShouldUseAlternSdk(boolean shouldUse, final JCheckBox useAlternativeSdkCB, final JComboBox alternativeSdksComboBox, final JComboBox myModulesComboBox)
  6. updateContents( @SuppressWarnings("rawtypes") JComboBox box, Object[] options)
  7. updateGooseChooser(JComboBox gooseChooser, String callingGoose, String[] allGeese)