Search code examples
javaswinglayout-managerboxlayout

Why does glue disappear when I wrap a Panel with another one?


Here's what I tried:

JPanel p1 = new JPanel();
BoxLayout b1 = new BoxLayout(p1, BoxLayout.X_AXIS);
p1.setLayout(b1);
p1.add(new JButton("1"));
p1.add(Box.createHorizontalGlue());
p1.add(new JButton("1"));

And it works pretty fine. The buttons are on the left and right sides

enter image description here

But if I wrap it into JPanel managed by FlowLayout the glue disappears.

//Flow Layout
JPanel jp = new JPanel();

//Box Layout
JPanel p1 = new JPanel();
BoxLayout b1 = new BoxLayout(p1, BoxLayout.X_AXIS);
p1.setLayout(b1);
p1.add(new JButton("1"));
p1.add(Box.createHorizontalGlue());
p1.add(new JButton("1"));

//put it into a JPanel with FlowLayout
jp.add(p1);
panel.add(jp);

Why? I thought the glue was just like any other componets, so it shouldn't dissapear. This is how it looks:

enter image description here

Can't someone explain it? Note, that if I put it into a JPanel with BoxLayout it's fine.


Solution

  • Why? I thought the glue was just like any other componets, so it shouldn't dissapear

    "glue" has a preferred size of 0.

    Can't someone explain it?

    A FlowLayout displays components at their preferred size. So any panel added to it will be displayed at the panels preferred size.

    The preferred size of a panel using a BoxLayout is the size of the components added to the panel. Since the preferred size of the glue is 0, it has no effect on the preferred size of the panel.

    The "glue" just gives added functionality to a panel using the BoxLayout. That is when the panel size (as determined by the layout manager of the parent panel) is greater than the preferred size, the BoxLayout will give the extra space to the glue.

    So depending on the layout manager of the parent panel, the "glue" will or will not affect the layout.