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);
}
}
source
share