Search code examples
javaswingjcombobox

Adapt JComboxBox maximumRowCount to JFrame or Screen Size


Everything is in the title.

In my application, depending on a selection made by the user I fill up a combobox with a list which can sometime be small (1 element) sometimes be large (150 elements).

What I would like is not to have a fixed height set at startup to a given value but to set the maximumRowCount to the height of my JFrame or to the height of my screen and I don't know how to determine the number of rows that would match my application height or my screen height. This should be dynamical (at runtime) so when I change the combobox font size the maximumRowCount also adapts itself.

Can anyone help me?


Solution

  • So you need to figure out how big each row in the drop-down list is. To do this, the easy way is to create a cell renderer, populate it, and ask it for its preferred height.

    final DefaultListCellRenderer dlcr = new DefaultListCellRenderer();
    dlcr.setText("one of my combo items");
    
    int numRows = (int)( (1.0f * frame.getHeight()) / dlcr.getPreferredSize().height );
    
    setMaximumRowCount(numRows);
    

    Note that I used frame.getHeight() here, but at least in some look-and-feels, the drop-down list starts below the combo box, so you'd have to make some adjustment for that. And there are ways to get the size of a screen, too, such as those in http://docs.oracle.com/javase/6/docs/api/java/awt/Toolkit.html.