Search code examples
javaswingjlabellayout-manager

Center two JLabels beneath each other, vertically


I've got to create two JLabels, and the should been positioned center and right under each other in the JFrame. I've beeing using the gridbaglayout from swing, but I can't figure out how to do this.

terminalLabel = new JLabel("No reader connected!", SwingConstants.CENTER);  
terminalLabel.setVerticalAlignment(SwingConstants.TOP); 

cardlabel = new JLabel("No card presented", SwingConstants.CENTER); 
cardlabel.setVerticalAlignment(SwingConstants.BOTTOM);

Solution

  • Use a BoxLayout. In the code below the Box class is a convenience class that creates a JPanel that uses a BoxLayout:

    import java.awt.*;
    import javax.swing.*;
    
    public class BoxExample extends JFrame
    {
        public BoxExample()
        {
            Box box = Box.createVerticalBox();
            add( box );
    
            JLabel above = new JLabel("Above");
            above.setAlignmentX(JLabel.CENTER_ALIGNMENT);
            box.add( above );
    
            JLabel below = new JLabel("Below");
            below.setAlignmentX(JLabel.CENTER_ALIGNMENT);
            box.add( below );
        }
    
        public static void main(String[] args)
        {
            BoxExample frame = new BoxExample();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
        }
    }