如果您的目标是使组件居中,那么
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());
}
}