简体   繁体   中英

Why buttons are not in the center in Java Swing?

Screenshot is here: 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. 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. It is typically used by IDE's. So I have no idea why the GroupLayout isn't doing whag you expect.

Instead I build my GUI's by hand using nested layouts when required.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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