首页 > 解决方案 > 使用 BoxLayout 垂直居中内容

问题描述

我正在尝试将 JPanel 的内容与 BoxLayout 垂直居中。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);
...

我怎么能把它改成垂直居中?

标签: javaswingjpanellayout-managerboxlayout

解决方案


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

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

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

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


推荐阅读