简体   繁体   中英

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

I want to align Labels and a Panel (containing Buttons) to the left inside a vertical BoxLayout.

As long as I don't add the panel to the BoxLayout everything is aligned to the left perfectly, but adding it screws everything up.

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);

    }
}

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

Your components need to have the same "x alignment":

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

Read the section from the Swing tutorial on Fixing Alignment Problems for more information.

You can use invisible components as fillers .

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

and then:

panel.add(leftAlignedInHorizontalBox(label1));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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