tags:

views:

310

answers:

4

Hi I am using a BoxLayout to stack JPanels on top of each other (BoxLayout.Y_AXIS), for example if my parent JPanel is of height 500 pixels and I add two child panels to it both of height 100 pixels. The BoxLayout stretches them so that together they occupy the the 500px space. Does anyone know how to disable this feature?

Thanks

+3  A: 

Use GridBagLayout instead. You have much more control over your UI.

But if you want to use BoxLayout still, and don't want them to stretch, you can check out using invisible component fillers like rigid areas, glue and fillers.

Ascalonian
A: 

Your panels are stretching because BoxLayout does not constrain each panel to its preferred size. You need to find layouts that do respect a component's preferred size, as BorderLayout's NORTH and SOUTH positions do.

Try this:

  1. Create a JPanel with a BorderLayout. Add your child component as NORTH in this JPanel.
  2. Create a second JPanel for the other child component, add it as NORTH of a BorderLayout
  3. Add the two JPanels to your BoxLayout.

Code:

JPanel panel1 = new JPanel(new BorderLayout());
panel1.add(component1, BorderLayout.NORTH);
JPanel panel2 = new JPanel(new BorderLayout());
panel2.add(component2, BorderLayout.NORTH);

JPanel boxPanel = new JPanel();
BoxLayout boxLayout = new BoxLayout(boxPanel, BoxLayout.Y_AXIS);
boxPanel.setLayout(boxLayout);
boxPanel.add(panel1);
boxPanel.add(panel2);
David
+1  A: 

The trick is, as the previous answer mentioned, to use the glue, fillers, and rigid areas in the box layout. Unlike that responder, though, I'd recommend sticking with BoxLayout - you can accomplish most simple UIs easier with Box than with the Grid Bag; and the extra power doesn't buy you much in your typical dialog box.

In the old idiom, these were things like Box.createHorizontalStrut(int x) and Box.createHorizontalGlue(); the idea is that you put a strut between your first and second components and then add a glue after the second one. ("strut" = "rigid area" nowadays).

M1EK
I will agree with that for general stacking purposes the GridBagLayout may be overkill. Just suggesting it if he goes forward.
Ascalonian
I have tried putting a rigid area between the two child panels and vertical glue after the second one, put the panels are still being stretched :s
Aly
There is no such thing as an overkill :)
willcodejavaforfood
Try adding a panel container for the bottom 2 panels, then sticking those two themselves in a box... I'm not clear on the arrangement you're looking for, but you can always come up with some combination of subpanels, struts, and glue that makes things not stretch.
M1EK
+1  A: 

BoxLayout is one of the few layout managers that respects the minimum and maximum sizes of a component. So if you want to prevent a panel from stretching you can use:

panel.setMaximumSize( panel.getPreferredSize() );
camickr