Search code examples
javaswinggridbaglayout

Swing GridBagLayout: centering a button on the second row


I have this code that displays a label, a textfield and a button:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Form extends JFrame implements ActionListener  {
    private JLabel label = new JLabel("What's your name:");
    private JTextField field = new JTextField(15);
    private JButton button = new JButton("Send");

    public Form()  {
        setTitle("Name Form");
        setLayout(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 1);
        gbc.anchor = GridBagConstraints.LINE_END;
        gbc.gridx = 0;
        gbc.gridy = 0;
        add(label, gbc);

        gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 1;
        gbc.gridy = 0;
        add(field, gbc);

        gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.anchor = GridBagConstraints.LINE_END;
        gbc.gridx = 0;
        gbc.gridy = 1;
        add(button, gbc);
    }

    @Override
    public void actionPerformed(ActionEvent event) {


    }

    public static void main(String[] args) {
        Form myFrame = new Form();

        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.pack();
        myFrame.setVisible(true);
    }

}

It shows this:

enter image description here

I need the button to be horizontally centered like this:

enter image description here

How do I do this with GridBagLayout? I tried different values for anchor but nothing worked.

EDIT:

Adding gbc.gridwidth = 2 showed this:

enter image description here


Solution

  • The button needs to stretch over the two columns, so set the gridwidth.

        gbc.gridwidth = 2;
    

    (Btw, you don't need to create a new GridBagConstraints for each component. Just reuse the say one and only change the properties that are different.)