如何将 JLabels 和 JPanels 对齐到 BoxLayout 中的左侧?

How to align JLabels and JPanels to the left inside BoxLayout?

我想在垂直 BoxLayout 中将标签和面板(包含按钮)左对齐。

只要我不将面板添加到 BoxLayout,所有内容都会完美地左对齐,但添加它会搞砸一切。

import javax.swing.*;
import java.awt.*;

public class BoxLayoutDemo{

    public static void main(String[] args) {

        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        JPanel five = new JPanel();
        JButton plus = new JButton("+");
        JButton minus = new JButton("-");

        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        Font testFont = new Font("Arial", Font.BOLD, 20);
        JLabel label1 = new JLabel("Label1");
        label1.setFont(testFont);
        JLabel label2 = new JLabel("Label2");
        label2.setFont(testFont);

        five.setLayout(new BoxLayout(five, BoxLayout.X_AXIS));

        plus.setMinimumSize(new Dimension(30, 30));
        plus.setMaximumSize(new Dimension(30, 30));

        minus.setMinimumSize(new Dimension(30, 30));
        minus.setMaximumSize(new Dimension(30, 30));

        five.add(plus);
        five.add(minus);

        panel.add(label1);
        panel.add(five);
        panel.add(label2);

        panel.setOpaque(true);
        panel.setBackground(Color.red);

        frame.setMinimumSize(new Dimension(200, 200));
        frame.getContentPane().add(panel, BorderLayout.EAST);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

    }
}

你可以use invisible components as fillers.

private static Box leftAlignedInHorizontalBox(Component component) {
    Box box = Box.createHorizontalBox();
    box.add(component);
    box.add(Box.createHorizontalGlue());
    return box;
}

然后:

panel.add(leftAlignedInHorizontalBox(label1));

您的组件需要具有相同的 "x alignment":

label1.setAlignmentX(Component.LEFT_ALIGNMENT);
label2.setAlignmentX(Component.LEFT_ALIGNMENT);
five.setAlignmentX(Component.LEFT_ALIGNMENT);

阅读 Fixing Alignment Problems 上的 Swing 教程部分了解更多信息。