java glue_在GUI上使用Glue,java

如果您的目标是使组件居中,那么

GridBagLayout将很好地完成工作:

public class CenteringPanel extends JPanel {

public CenteringPanel(JComponent child) {

GridBagLayout gbl = new GridBagLayout();

setLayout(gbl);

GridBagConstraints c = new GridBagConstraints();

c.gridwidth = GridBagConstraints.REMAINDER;

gbl.setConstraints(child, c);

add(child);

}

}

GridBagLayout将创建一个填充面板的单个单元格.约束的默认值是水平和垂直对齐其单元格中的每个组件,并且既不填充方向.

如果你的目标是在BoxLayout中使用Glue来集中组件,那么这项工作就会复杂一些.使用垂直BoxLayout添加水平胶水没有帮助,因为组件是垂直堆叠的(对于水平BoxLayout也是如此).相反,您需要限制子项的大小并使用其对齐方式.我没有尝试过,但是对于垂直的BoxLayout,这样的东西应该可以工作:

public class CenteringPanel {

public CenteringPanel(JComponent child) {

setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

GridBagConstraints c = new GridBagConstraints();

child.setMaximumSize(child.getPreferredSize());

child.setAlignmentX(Component.CENTER_ALIGNMENT);

add(Box.createVerticalGlue());

add(child);

add(Box.createVerticalGlue());

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值