Center two JLabels under each other, vertically

I need to create two JLabels, and they should be located in the center and to the right of each other in the JFrame. I use a gridbaglayout from a swing, but I cannot 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);
+5
source share
4 answers

Use BoxLayout. In the code below, the Box class is a convenience class that creates a JPanel that uses 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);
    }
}
+8
source

Using FlowLayout and GridLayout

enclosingPanel = new JPanel();
enclosingPanel.setLayout( new FlowLayout( FlowLayout.CENTER) );
labelPanel = new JPanel();
labelPanel.setLayout( new GridLayout( 2 , 1 ) );  // 2 rows 1 column
enclosingPanel.add( labelPanel );
frame.add( enclosingPanel );  // frame = new JFrame();
setPreferredSize( new Dimension( 200 , 200) );
// do other things

, 2 JLabels . . # GridLayout (int, int, int, int)

+2

You must specify the correct CENTER for the GridBagCOnstraints, which you use to add labels to the container.

+1
source

You must use GridBagConstraints. Change the gridYvalue of the constraints when adding a second label, and it will be placed under the first.

Try the following:

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200, 200);
    frame.setLayout(new GridBagLayout());
    GridBagConstraints constraints = new GridBagConstraints();

    constraints.gridx = 0;
    constraints.gridy = 0;
    constraints.anchor = GridBagConstraints.CENTER;
    JLabel terminalLabel = new JLabel("No reader connected!");  
    frame.add(terminalLabel,constraints);

    constraints.gridy = 1;
    JLabel cardlabel = new JLabel("No card presented"); 
    frame.add(cardlabel,constraints);

    frame.setVisible(true);

Also read this: How to use GridBagLayout

+1
source