简体   繁体   English

为什么按钮不在Java Swing中居中?

[英]Why buttons are not in the center in Java Swing?

Screenshot is here: http://imgur.com/a/33rhe 屏幕截图在这里: http : //imgur.com/a/33rhe

在此处输入图片说明

I'm using this code: 我正在使用此代码:

layout.setHorizontalGroup(
        layout.createSequentialGroup()
            .addComponent(greeting)
            .addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
                    .addGap(0,0,Short.MAX_VALUE)
                        .addComponent(english)
                        .addComponent(german)
                        .addComponent(french))
            .addGroup(layout.createSequentialGroup()
                .addGap(0,0,Short.MAX_VALUE)
                .addComponent(quit))
    );

So with this GroupLayout.Alignment.CENTER I'm expecting that my buttons will be centralized, but they are not in the center on render. 因此,使用此GroupLayout.Alignment.CENTER我希望按钮可以集中显示,但是它们不在渲染的中心。 What is the problem? 问题是什么? What I did wrong? 我做错了什么?

I'm a newbie and trying to understand what is going there 我是新手,想了解那里发生的事情

I never manually use a GroupLayout. 我从不手动使用GroupLayout。 It is typically used by IDE's. 它通常由IDE使用。 So I have no idea why the GroupLayout isn't doing whag you expect. 所以我不知道为什么GroupLayout没有按照您的期望做。

Instead I build my GUI's by hand using nested layouts when required. 相反,我在需要时使用嵌套布局手动构建GUI。

So instead I would do something like: 因此,我将改为:

JPanel buttonPanel = new JPanel( new GridLayout(...) );
buttonPanel.add(...);

frame.setLayout( new GridBagLayout() );
frame.add(buttonPanel, new GridBagConstraints());

Now the "buttonPanel" will be centered both vertically and horizontally. 现在,“ buttonPanel”将在垂直和水平方向居中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM