tags:

views:

692

answers:

4

I want to build a dialog in Java with a List and a couple of buttons underneath it. The list ends up with the same height as the buttons (about one line) and the whole dialog is about two lines of height.

However, I'd like the dialog to be taller (maybe 10 lines) and the JList to take up most of the space .. I've played around with the parameters, but for the life of it can't get it to work. Any ideas?

Here's my current code:

//layout
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;

int y = 0;
//List
gbc.gridx = 0;
gbc.gridy = y;
gbc.weighty = 3;
gbc.weightx = 1;
gbc.gridwidth= 3;
add(new JScrollPane(_myList), gbc);
_myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

// Buttons
gbc.gridx = 1;
gbc.gridy = ++y;
gbc.gridwidth = 1;
gbc.weighty = 0;
add(_Save, gbc);
gbc.gridx = 2;
add(_Cancel, gbc);
A: 

I've done some more poling around, and apparently the behaviour is caused by the number of items in the ListModel of _myList. When I populate it with a larger number of items than the one or two it has in my current usage, then the list is properly displayed. Hopefully that helps to pin down the problem and find a solution ..

IronGoofy
+2  A: 

For the list set weightY=1 instead of 3. The setting of 3 will make the space for the list larger than the list itself. 99.9% of the time GridBagLayout is used the weightX/Y values should always be either 0 or 1. Also the gridWidth should probably be 2 instead of 3.

John Meagher
Thanks, but the problem was somewhere else in my code.
IronGoofy
+1 This actually helped me with the problem I had. Setting weighty to a JScrollPane (that has a JList) will appropriately resize the component vertically.
Spoike
A: 

Found the problem .. and it has nothing to do with the layout code.

I was adding a null to ListModel, and that seemed to confuse the LayoutManager. Would close the question, but not yet enough mojo ...

IronGoofy
+1  A: 

You might as well consider calling _myList.setVisibleRowCount(n) to force a preferred size (in number of visible rows) for your list.

jfpoilpret
I tried, but it didn't change anything with the null entries. For general sizing it sure works so +1
IronGoofy