简体   繁体   中英

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

在此输入图像描述

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:

在此输入图像描述

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM