在 JLabel 之间创建垂直 space 未按预期进行

Creating vertical space between JLabels not going as expected

我想在 JLabel 之间创建一个垂直 space。这是我的代码:

    JPanel label = new JPanel(new FlowLayout(FlowLayout.LEFT));
    label.add(Box.createVerticalStrut(50));
    label.add(label1);
    label.add(Box.createHorizontalStrut(50));
    label.add(label2);
    label.add(Box.createVerticalStrut(50));
    label.add(label3);
    label.add(Box.createHorizontalStrut(50));
    label.add(label4);

我想在每个 JLabel 之间有相等的垂直 space,但是,当我调整 Box.createHorizontalStrut(50) 时它变得很奇怪 有人知道为什么吗? FlowLayout 用于将 JLabel 定位到面板的左侧。据此,我想将一些 JLabel 定位在中心(因此水平移动),是否有另一种方法可以通过 FlowLayout?

谢谢。

I want to create a vertical space between JLabels

那么你应该使用 BoxLayout。阅读 Swing 教程中关于 How to Use BoxLayout 的部分以获取工作示例。

The FlowLayout is done to position the JLabels to the left of the panel. In accordance with this

然后您可以在每个标签上使用 setAlignmentX(0.0f)。然后 BoxLayout 会将标签左对齐。

I want to position some of the JLabels in the center

我相信这是标签对齐的默认值(每个组件都不同),因此您无需执行任何操作。但是如果你想确保你总是可以在标签上使用 setAlignment(0.5f)