【问题标题】:Vertically center content with BoxLayout使用 BoxLayout 垂直居中内容
【发布时间】:2020-06-10 19:29:28
【问题描述】:

我正在尝试将带有 BoxLayout 的 JPanel 的内容垂直居中。 BoxLayout 与 Y 轴对齐,因此里面的项目是水平对齐的。

例如,我现在拥有的:

-----------------------------
|          ------           |
|        ----------         |
|           ----            |
|      --------------       |
|                           |
|                           |
|                           |
|                           |
|                           |
|                           |
-----------------------------

我想要什么:

-----------------------------
|                           |
|                           |
|                           |
|          ------           |
|        ----------         |
|           ----            |
|      --------------       |
|                           |
|                           |
|                           |
-----------------------------

目前,我正在使用 setAlignmentX(Component.CENTER_ALIGNMENT) 将元素列居中:

JPanel box = new JPanel();
box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS));
JLabel one = new JLabel("First element");
one.setAlignmentX(JLabel.CENTER_ALIGNMENT);
box.add(one);
JLabel two = new JLabel("Second element");
two.setAlignmentX(JLabel.CENTER_ALIGNMENT);
box.add(two);
...

如何将其更改为垂直居中?

【问题讨论】:

    标签: java swing jpanel layout-manager boxlayout


    【解决方案1】:

    BoxLayout 布局允许组件在有额外空间可用时增长(达到最大大小)。

    您需要添加允许增长的组件。基本代码是:

    box.add( Box.createVerticalGlue() );
    box.add(...);
    box.add( Box.createVerticalGlue() );
    

    顶部/底部的两个“胶水”组件将增长以填满可用空间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-10
      • 2017-08-16
      • 2015-03-01
      • 2017-12-13
      • 1970-01-01
      • 1970-01-01
      • 2014-11-28
      相关资源
      最近更新 更多