我试图将 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);
...
如何将其更改为垂直居中?
最佳答案
当有额外空间可用时,BoxLayout
布局允许组件增长(直至最大尺寸)。
您需要添加允许增长的组件。基本代码是:
box.add( Box.createVerticalGlue() );
box.add(...);
box.add( Box.createVerticalGlue() );
顶部/底部的两个“粘合”组件将增长以填充可用空间。
关于java - 使用 BoxLayout 垂直居中内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60422149/