3

I've got the following form which uses a vertical BoxLayout and FlowLayout JPanels for rows:

enter image description here

How can I make the huge gap between each row smaller? This is my code:

2
  • 2
    For better help sooner, please include an SSCCE.
    – mre
    Commented Feb 1, 2013 at 18:38
  • Piece of advice, don't use setPreferredSize(). This is just fighting against Swing instead of workinf with it. Commented Feb 1, 2013 at 21:05

3 Answers 3

13

The problem is that the BoxLayout respects the maximum size of the components. Since panels don't have a maximum size each panel increases in height to take up the available space.

Another solution is to determine the maximum size of each panel after you add the components to the panel:

pnlName.setMaximumSize( pnlName.getPreferredSize() );
pnlSurname.setMaximumSize( pnlSurname.getPreferredSize() );
pnlAge.setMaximumSize( pnlAge.getPreferredSize() );
0
5

You can use glue (invisible component) to fill free space. See this doc

Instead of a box layout, you can also use a VerticalLayout. Unfortunatelly, it doesn't exist in swing api, but there are lot of free implementation of such layout available.

for instance : http://www.java2s.com/Code/Java/Swing-JFC/AverticallayoutmanagersimilartojavaawtFlowLayout.htm

4

What you need is greedy glue. Unless the glue is greedy it and its siblings all receive a portion of any extra space. A glue is a Box.Filler object and has a method changeShape to reset its size constraints. To make it greedy, set the preferred size to Integer.MAX_VALUE:

    Box.Filler glue = Box.createVerticalGlue();
    glue.changeShape(glue.getMinimumSize(), 
                    new Dimension(0, Short.MAX_VALUE), // make glue greedy
                    glue.getMaximumSize());

Add this glue element as the last item in your outer box.

1
  • 1
    I had to cast to Box.Filler in the first line: Box.Filler glue = (Box.Filler) Box.createVerticalGlue();
    – Kyle
    Commented Jan 12, 2020 at 17:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.