Search code examples
javaswingjlabelboxlayout

How to center JLabel in a panel with BoxLayout


I'm a newbie in Java programming and I got a question about BoxLayout. I can't get the JLabels centered in a panel with BoxLayout

What I want is to change from what I got now:

https://i.sstatic.net/12aB7.png

to this:

https://i.sstatic.net/IC68C.png

getting the labels being totally in the middle of the panel.

Here's my code:

import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Test extends JFrame{

    private JLabel label1;
    private JLabel label2;
    private JLabel label3;
    private JLabel label4;
    private JLabel label5;

    public Test(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initWidgets();
        setVisible(true);
    }

    private void initWidgets(){
        setPreferredSize(new Dimension(300, 300));

        label1 = new JLabel("Label 1");
        label2 = new JLabel("Label 2");
        label3 = new JLabel("Label 3");
        label4 = new JLabel("Label 4");
        label5 = new JLabel("Label 5");

        JPanel jpanel = new JPanel();

        label1.setAlignmentX(CENTER_ALIGNMENT);
        label2.setAlignmentX(CENTER_ALIGNMENT);
        label3.setAlignmentX(CENTER_ALIGNMENT);
        label4.setAlignmentX(CENTER_ALIGNMENT);
        label5.setAlignmentX(CENTER_ALIGNMENT);

        jpanel.setLayout(new BoxLayout(jpanel, BoxLayout.PAGE_AXIS));

        jpanel.add(label1);
        jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
        jpanel.add(label2);
        jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
        jpanel.add(label3);
        jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
        jpanel.add(label4);
        jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
        jpanel.add(label5);

        add(jpanel);
        pack();
    }

    public static void main(String[] args) {
        new Test();
    }
}

Solution

  • To vertically center the components you need to add "glue" at the start and end:

    jpanel.add(Box.createVerticalGlue());
    jpanel.add(label1);
    jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
    jpanel.add(label2);
    jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
    jpanel.add(label3);
    jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
    jpanel.add(label4);
    jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
    jpanel.add(label5);
    jpanel.add(Box.createVerticalGlue());
    

    Read the section from the Swing tutorial on How to Use BoxLayout for more information.