Java-如何将组件的垂直列居中? [英] Java - how to center vertical column of components?

查看:758
本文介绍了Java-如何将组件的垂直列居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很简单,我想做什么,但我想不出一种方法.在JFrame或JPanel中,如何使组件垂直居中?也就是说,类似于在HTML中使用center标签.组件位于一列中,并且全部居中.

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.

我尝试了BoxLayout和Y_AXIS和PAGE_AXIS,但对我来说,它以一种奇怪的方式对齐了组件.我尝试使用具有首选大小设置的FlowLayout来环绕它,但是它不会居中.除非它确实是唯一的选择,否则我不愿意使用像GridBagLayout这样的功能强大的东西来做这样简单的事情.帮助!

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!

推荐答案

如果我不得不猜测,我会说您正在使用具有不同"x对齐"的组件.尝试使用:

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

有关更多信息,请参见修复对齐问题的Swing教程中的部分.信息.

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

如果您需要更多帮助,请发布 SSCCE ,其中显示了您尝试过的内容.

If you need more help then post your SSCCE showing what you have tried.

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

这篇关于Java-如何将组件的垂直列居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆