简体   繁体   English

使用 BoxLayout 垂直居中内容

[英]Vertically center content with BoxLayout

I'm trying to center the content of a JPanel with BoxLayout vertically.我试图将带有 BoxLayout 的 JPanel 的内容垂直居中。 The BoxLayout is aligned to the Y-axis, so items inside are aligned horizontally. BoxLayout 与 Y 轴对齐,因此里面的项目水平对齐。

For example, what I have now:例如,我现在拥有的:

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

What I want:我想要的是:

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

At the moment, I'm centering the column of elements using setAlignmentX(Component.CENTER_ALIGNMENT):目前,我正在使用 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);
...

How could I change this to also be vertically centered?我怎样才能将其更改为垂直居中?

The BoxLayout layout allows components to grow (up to their maximum size) when extra space is available.当有额外空间可用时, BoxLayout布局允许组件增长(达到它们的最大大小)。

You need to add components that are allowed to grow.您需要添加允许增长的组件。 The basic code would be:基本代码是:

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

The two "glue" components on the top/bottom will grow to fill available space.顶部/底部的两个“胶水”组件将增长以填充可用空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM