Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 997
Tobias Moe Thorstensen Avatar asked Aug 03 '11 05:08

Tobias Moe Thorstensen


1 Answers

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);
    }
}
like image 67
camickr Avatar answered Sep 30 '22 07:09

camickr