java layout组件居中,Java-如何将组件的垂直列居中?

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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值