【问题标题】:Align JButtons in center of nested JPanel (BoxLayout)在嵌套的 JPanel (BoxLayout) 的中心对齐 JButton
【发布时间】:2017-03-24 19:26:21
【问题描述】:

我有一个JFrame 的子类,里面有followiwng 布局。我有一个大的panel 和一个小的buttonsPanel 和两个JButtons。我将按钮添加到较小的面板并将该面板添加到第一个面板。按钮应该居中,但它不会发生。

panel=new JPanel();
add(panel);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

JButton button1=new JButton("button1");
JButton button2=new JButton("button2");

buttonsPanel=new JPanel();
buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS));

buttonsPanel.add(button1, CENTER_ALIGNMENT);
buttonsPanel.add(button2, CENTER_ALIGNMENT);
panel.add(buttonsPanel, BorderLayout.CENTER);

我该怎么办?

【问题讨论】:

  • 应该是垂直居中,还是水平居中?
  • @VGR,水平。

标签: java swing jbutton layout-manager boxlayout


【解决方案1】:

您确实需要阅读 Layout Managers 上的 Swing 教程。您需要了解什么是“约束”以及何时使用它。

buttonsPanel.add(button1, CENTER_ALIGNMENT);

按钮面板使用 BoxLayout。它不支持任何约束,因此 CENTER_ALIGNMENT 没有意义。

panel.add(buttonsPanel, BorderLayout.CENTER);

同样,面板使用 BoxLayout。您不能只使用 BorderLayout 约束。

使组件居中(在框架上垂直和水平方向)最简单的方法是使用 GridBagLayout。

所以基本代码可能是这样的:

JPanel buttonsPanel = new JPanel();
buttonsPanel.add(button1);
buttonsPanel.add(button2);

frame.setLayout( new GridBagLayout() );
frame.add(buttonsPanel, new GridBagConstraints());

如果你想尝试使用 BoxLayout 那么你需要在面板前后使用“胶水”:

Box vertical = Box.createVerticalBox();
vertical.add(Box.createVerticalGlue());
vertical.add(buttonsPanel);
vertical.add(Box.createVerticalGlue());

再次阅读教程,了解有关BoxLayout 的更多基本信息。

【讨论】:

  • 我在添加buttonsPanel之前和之后添加了胶水panel.add(Box.createVerticalGlue()),删除了错误的约束,但它仍然不起作用。并且胶水增加了空格......
  • @parsecer 这正是胶水应该做的,在顶部和底部添加空间,使组件在中间垂直居中。如果代码未按您预期的方式运行,请发布正确的minimal reproducible example 来说明问题。
猜你喜欢
  • 2014-04-30
  • 2012-07-28
  • 1970-01-01
  • 2016-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多