Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - how to center vertical column of components?

It's very simple, what I want to do, but I can't figure out a way to do it. In a JFrame or JPanel, how do you center components vertically? That is, analogous to using the center tag in HTML. The components are in a column and they are all centered.

I have tried BoxLayout, with Y_AXIS and PAGE_AXIS, but it aligns the components in a strange way for me. I have tried to use FlowLayout with preferred size set so it wraps around, but it doesn't center it. I'd rather not resort to something powerful like GridBagLayout for such a simple thing unless it is really the only option. Help!

like image 619
Shelley Avatar asked Jul 10 '11 02:07

Shelley


1 Answers

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

component.setAlignmentX(JComponent.CENTER_ALIGNMENT);

See the section from the Swing tutorial on Fixing Alignment Problems for more information.

If you need more help then post your 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);
    }
}
like image 97
camickr Avatar answered Oct 23 '22 11:10

camickr