NetBeans, GUI builder (group layout) centering a component
Asked Answered
T

5

7

I'm trying to design a JButton (an "Ok" button) that to look good has to be horizontally centered in the containing JFrame.
I'm using the GUI Builder with the Free Form layout (GroupLayout).

I've taken several GUI builder tutorials (http://netbeans.org/kb/docs/java/quickstart-gui.html) but haven't found this topic. In other gui builders (delphi) this can be done by removing the anchors from both edges.

Television answered 10/10, 2011 at 10:17 Comment(0)
T
5

If you want your component to remain centered in its container if the container is resized, you have several options available to you, but I don't think that GroupLayout is one of them (please correct me if I'm wrong). One way is to change the container's layout to GridBagLayout, and then simply add the JButton into it without any constraints.

Thier answered 10/10, 2011 at 10:56 Comment(8)
the case (i think it is very frequent) is that you have a form with many controls. The layout of the controls makes the GroupLayout a perfect choice. Except for the button at the end, that should be centered. Of course i can put a JPanel at the end of the page, make it horizontally resizable and put into its (default) centered FlowLayout the JButton. But the question arises from the fact that in other GUI builders (not so sophisticated) like Delphi's one, the centering is a birllant extension of anchoring logic. Not anchoring a control to anywhere means let it "float" at the center.Television
@Television you will have a lots of surprise with this LayoutManager Pete +1Charinile
@mKorbel, i'm not so glad to hear that :-). can you provide a few samples?Television
for what, about what 1) check Hovercraft Full Of Eels history, he loves this LayoutManager 2) I know that childish but basic examples from download.oracle.com/javase/tutorial/uiswing/layout/index.html shows all possible :-), 3) java2s.com/Tutorial/Java/0240__Swing/1460__GridBagLayout.htm, 4) java2s.com/Tutorial/Java/0240__Swing/…,Charinile
@Television this topic Centering JComponent is solved lots of times on this forum,Charinile
@mKorbel. the question was if it is possible center a component via GroupLayout. there are plenty of ways to have a component centered with other layouts. Since I have provide one way myself, it's supposed that I'm not searching for something that we (me included) already know, but something else. A bit more precise.Television
accepted as there are no supported ways in order to center a component with GroupLayout, and probably won't ever be. It was intended as a GroupLayout improvement to avoid nesting another Layout manager, but swing is hardly mantained and it's very unlikely to have such type of improvements.Television
GroupLayout has been underestimated here. It can center components. See my answer. (I think that its capability to center components has not been added just recently -- it was also possible two years ago when the question was asked.)Mckale
M
7

GroupLayout does support centering of components. It is a very capable layout manager. I personally put it after the MigLayout manager and before the FormLayout manager.

In the following three examples, we have a panel and a button. The button is horizontally centered.

Centering with NetBeans Builder

To center a component using a Netbeans Builder, we need to create horizontal resizable gaps from both sides of the button.

The green area of the screenshot is a currently selected gaps. The strings inside the gaps suggest that it is a resizable gap.

NetBeans screenshot

The gaps are automatically added when we place components on the form. To define a gap to be resizable, we right click on the gap and select the "Edit Layout Space" option. We get the following dialog:

NetBeans screenshot

To get a resizable gap, we check the Resizable check box.

Centering manually by using a parallel group

Components can be centered in the parallel group by passing the GroupLayout.Alignment.CENTER parameter.

package com.zetcode;

import java.awt.Container;
import java.awt.EventQueue;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import static javax.swing.GroupLayout.Alignment.CENTER;
import static javax.swing.GroupLayout.DEFAULT_SIZE;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class GroupLayoutCenter extends JFrame {

    public GroupLayoutCenter() {

        initUI();

        setTitle("Centered button");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);        
    }

    private void initUI() {

        Container pane = getContentPane();
        GroupLayout gl = new GroupLayout(pane);
        pane.setLayout(gl);    

        gl.setAutoCreateGaps(true);
        gl.setAutoCreateContainerGaps(true);

        JPanel pnl = new JPanel();
        pnl.setBorder(BorderFactory.createEtchedBorder());

        JButton btn = new JButton("Button");

        gl.setHorizontalGroup(gl.createParallelGroup(CENTER)
           .addComponent(pnl, DEFAULT_SIZE, 200, DEFAULT_SIZE)
           .addComponent(btn)
        );

        gl.setVerticalGroup(gl.createSequentialGroup()
           .addComponent(pnl, DEFAULT_SIZE, 200, DEFAULT_SIZE)
           .addComponent(btn)            
        );          

        pack();
    }


    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                GroupLayoutCenter ex = new GroupLayoutCenter();
                ex.setVisible(true);
            }
        });
    }
}

Centering manually by using gaps

This solution is what NetBeans generated code does. We place two resizable gaps to the left and right sides of the button.

package com.zetcode;

import java.awt.Container;
import java.awt.EventQueue;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import static javax.swing.GroupLayout.DEFAULT_SIZE;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class GroupLayoutCenter2 extends JFrame {

    public GroupLayoutCenter2() {

        initUI();

        setTitle("Centered button");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);        
    }

    private void initUI() {

        Container pane = getContentPane();
        GroupLayout gl = new GroupLayout(pane);
        pane.setLayout(gl);    

        gl.setAutoCreateGaps(true);
        gl.setAutoCreateContainerGaps(true);

        JPanel pnl = new JPanel();
        pnl.setBorder(BorderFactory.createEtchedBorder());

        JButton btn = new JButton("Button");

        gl.setHorizontalGroup(gl.createParallelGroup()
                .addComponent(pnl, DEFAULT_SIZE, 200, DEFAULT_SIZE)
                .addGroup(gl.createSequentialGroup()
                        .addGap(5, 100, Short.MAX_VALUE)
                        .addComponent(btn)
                        .addGap(5, 100, Short.MAX_VALUE))
        );

        gl.setVerticalGroup(gl.createSequentialGroup()
                .addComponent(pnl, DEFAULT_SIZE, 200, DEFAULT_SIZE)
                .addComponent(btn)
        );    

        pack();
    }


    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                GroupLayoutCenter2 ex = new GroupLayoutCenter2();
                ex.setVisible(true);
            }
        });
    }
}

enter image description here

Mckale answered 6/8, 2014 at 22:30 Comment(0)
T
5

If you want your component to remain centered in its container if the container is resized, you have several options available to you, but I don't think that GroupLayout is one of them (please correct me if I'm wrong). One way is to change the container's layout to GridBagLayout, and then simply add the JButton into it without any constraints.

Thier answered 10/10, 2011 at 10:56 Comment(8)
the case (i think it is very frequent) is that you have a form with many controls. The layout of the controls makes the GroupLayout a perfect choice. Except for the button at the end, that should be centered. Of course i can put a JPanel at the end of the page, make it horizontally resizable and put into its (default) centered FlowLayout the JButton. But the question arises from the fact that in other GUI builders (not so sophisticated) like Delphi's one, the centering is a birllant extension of anchoring logic. Not anchoring a control to anywhere means let it "float" at the center.Television
@Television you will have a lots of surprise with this LayoutManager Pete +1Charinile
@mKorbel, i'm not so glad to hear that :-). can you provide a few samples?Television
for what, about what 1) check Hovercraft Full Of Eels history, he loves this LayoutManager 2) I know that childish but basic examples from download.oracle.com/javase/tutorial/uiswing/layout/index.html shows all possible :-), 3) java2s.com/Tutorial/Java/0240__Swing/1460__GridBagLayout.htm, 4) java2s.com/Tutorial/Java/0240__Swing/…,Charinile
@Television this topic Centering JComponent is solved lots of times on this forum,Charinile
@mKorbel. the question was if it is possible center a component via GroupLayout. there are plenty of ways to have a component centered with other layouts. Since I have provide one way myself, it's supposed that I'm not searching for something that we (me included) already know, but something else. A bit more precise.Television
accepted as there are no supported ways in order to center a component with GroupLayout, and probably won't ever be. It was intended as a GroupLayout improvement to avoid nesting another Layout manager, but swing is hardly mantained and it's very unlikely to have such type of improvements.Television
GroupLayout has been underestimated here. It can center components. See my answer. (I think that its capability to center components has not been added just recently -- it was also possible two years ago when the question was asked.)Mckale
P
2

Try GridbagLayout See this

Palikar answered 10/10, 2011 at 11:12 Comment(0)
D
2

Try another LayoutManager! GroupLayout is very obscure when just looking at the code generated by NetBeans.

If you used DesignGridLayout then what you need is as simple as:

DesignGridLayout layout = new DesignGridLayout(container);
layout.row().center().add(okButton);
Dissemblance answered 10/10, 2011 at 12:33 Comment(2)
@ jfpoilpret: does it provide a gui builder?Television
There's no need for a GUI builder when using designGridLayout, that's its force! The code you write directly expresses the layout you want. And just reading the code gives you an immediate vision of the obtained layout. No GUI builder, no ugly or complex code generation, that eases maintenance a lot, in addition to easing initial coding. DesignGridLayout API is very easy, you can understand how to use it and make your own layouts after only one or two hours reading the introduction and the examples on the web site.Dissemblance
M
2

javax.swing.Box.Filler can be used to pad space around a component inside a GroupLayout. In NetBeans Matisse (GUI Builder) they're called 'Horizontal Strut' under the 'Swing Fillers' section of the palette. Just put one on either side of your button, size them to fill all the empty space between the button and the edge of the container, and make sure they're both flagged to Auto Resize Horizontally.

As for using another LayoutManager, I know people don't like GroupLayout because it is not conducive to manual coding. That is by design. As the docs say, GroupLayout is intended to be used by GUI builders. So as long as you're ok with tying yourself to using NetBeans & Matisse for the life of your GUI, GroupLayout is really the best option.

Mooneyham answered 26/3, 2012 at 19:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.