繁体   English   中英

如何将 JLabels 和 JPanel 对齐到 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);

    }
}

这就是它的样子这就是它的样子

您的组件需要具有相同的“x 对齐”:

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

阅读 Swing 教程中有关修复 Alignment 问题的部分以获取更多信息。

您可以使用不可见的组件作为填充物

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

接着:

panel.add(leftAlignedInHorizontalBox(label1));

暂无
暂无

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

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