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!
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);
}
}
精彩评论