How to center a vertical column of components?

It is very simple what I want to do, but I cannot figure out how to do it. In JFrame or JPanel, how do you center components vertically? That is similar to using a central tag in HTML. The components are in a column and they are all centered.

I tried BoxLayout with Y_AXIS and PAGE_AXIS, but for me it weirdly aligns components. I tried using FlowLayout with a preferred size so that it turns around, but it does not center it. I would prefer not to resort to something powerful like GridBagLayout for such a simple thing, unless that is the only option. Help!

+5
source share
1 answer

If I had to make an assumption, I would say that you are using components with a different "x alignment". Try using:

component.setAlignmentX(JComponent.CENTER_ALIGNMENT);

For more information, see the section in the Swing manual on “Problems Configuring Reconciliation .

If you need more help, post an SSCCE showing what you have tried.

Edit:

import java.awt.*;
import javax.swing.*;

public class BoxLayoutTest extends JFrame
{
    public BoxLayoutTest()
    {
        Box box = new Box(BoxLayout.Y_AXIS);
        add( box );

        JLabel label = new JLabel("I'm centered");
        label.setAlignmentX(JComponent.CENTER_ALIGNMENT);

        box.add( Box.createVerticalGlue() );
        box.add( label );
        box.add( Box.createVerticalGlue() );
    }

    public static void main(String[] args)
    {
        BoxLayoutTest frame = new BoxLayoutTest();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.setSize(300, 300);
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}
+8
source

All Articles