Skip to content

How to place GUI components in java in the center?

I’m trying to create a mini form, that suppose to look like this:

like this

So far I got this:

my form

The problem is that I need to have this gap from the left, so that my form will be at the center, but I don’t know how to achieve this.

My code:

public class Person extends ClubAbstractEntity
    protected String id;
    protected String name;
    protected String surname;
    protected String tel;
    public Person(String id,String name,String surname,String tel)
        JLabel[] labels={new JLabel("Id", JLabel.RIGHT),new JLabel("Name", JLabel.RIGHT),new JLabel("Surname", JLabel.RIGHT),new JLabel("Tel", JLabel.RIGHT)};
        JTextField[] textFields=new JTextField[labels.length];
        JPanel container=new JPanel();
        container.setLayout(new BorderLayout());
        JPanel labelPanel = new JPanel(new GridLayout(labels.length, 1));
        JPanel fieldPanel = new JPanel(new GridLayout(labels.length, 1));
        container.add(labelPanel, BorderLayout.WEST);
        container.add(fieldPanel, BorderLayout.CENTER);
        for(int i=0;i<labels.length;i++)
            textFields[i]=new JTextField(30);
            JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));

It uses its parent (a class that extends JFrame) method called addToCenter which gets a GUI component and add it to the center.

protected void addToCenter(Component guiComponent)



The easiest way is to use a wrapper panel that uses the GridBagLayout with the default GridBagConstraints.

JPanel wrapper = new JPanel( new GridBagLayout() );
wrapper.add(container, new GridBagConstraints());

Now the “container” panel will be centered within the “wrapper” panel and the wrapper panel will fill all the available space in the frame. Read the section from the Swing tutorial on How to Use GridBagLayout

The section on using the weightx/weighty constraints will explain why this works.


Another option is to use a Border on parent panel. A Border allows you to reserve space or add highlights to a component. In this case you can use an EmptyBorder. Read the section from the Swing tutorial on How to Use Borders for more information and examples.

The difference between the two solution is that a Border is a fixed size, which works fine if the frame is not resizable. The “wrapper” panel solution works good if the frame is resizable as the panel will continually be centered in the space available as the frame is resized.

User contributions licensed under: CC BY-SA
1 People found this is helpful