Search code examples
javaswingjlabellayout-managerboxlayout

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

    }
}

That's how it look That's how it look


Solution

  • 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.