Java (Swing): Influence of JList height in GridBagLayout

I want to create a dialog in Java with a list box and several buttons below it. The list ends at the same height as the buttons (about one line), and the entire dialog is about two lines high.

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

Here is 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);

      

0


source to share


4 answers


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



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

0


source


For the list, set the weight to Y = 1 instead of 3. Setting 3 will make the space for the list larger than the list itself. 99.9% of the time a GridBagLayout is used, weightX / Y values ​​should always be either 0 or 1. Also, gridWidth should be 2 instead of 3.



+2


source


You might also consider calling _myList.setVisibleRowCount(n)

to force the preferred size (in the number of visible rows) for your list.

+1


source


I did some more operations and it seems the behavior is caused by the number of items in the ListModel _myList. When I fill it with more items than this or that it has in my current use, the list is displayed correctly. Hope this helps solve the problem and find a solution.

0


source







All Articles