Skip to content
Advertisement

Can’t span and left align text field in GridBagLayout

I have this code:

import javax.swing.*;
import java.awt.*;

public class Test extends JFrame {
    public Test()  {
        setLocationByPlatform(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLocationByPlatform(true);

        GridBagConstraints constraints = new GridBagConstraints();
        constraints.anchor = GridBagConstraints.LINE_START;
        constraints.insets = new Insets(5, 5, 0, 5);

        JRadioButton button1 = new JRadioButton("Aaaaaaaaa");
        JRadioButton button2 = new JRadioButton("Bbbb");
        JRadioButton button3 = new JRadioButton("cccccC");

        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());

        panel.add(new JLabel("Test"), createConstraints(0, 0));
        panel.add(button1, createConstraints(0, 1));
        panel.add(button2, createConstraints(1, 1));
        panel.add(button3, createConstraints(2, 1));

        JTextField text = new JTextField();
        GridBagConstraints c = createConstraints(0, 2);
        c.gridwidth = 3;
        panel.add(text, c);

        add(panel, BorderLayout.PAGE_START);

        setSize(350, 360);
        setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            Test frame = new Test();
            frame.setVisible(true);
        });
    }

    private GridBagConstraints createConstraints(int x, int y) {
        GridBagConstraints c = new GridBagConstraints();
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(5, 5, 0, 5);
        c.gridx = x;
        c.gridy = y;
        return c;
    }
}

It creates:

enter image description here

But I need the text field to always span 2 columns and everything to be left aligned:

enter image description here

How do I do that?

Advertisement

Answer

c.gridwidth = 3;

Needs to be:

c.gridwidth = 2; // unless it should fill all THREE columns!
c.fill = GridBagConstraints.HORIZONTAL;

Result:

enter image description here

Edit

As an aside. ‘Spanning two cells’ seems an entirely arbitrary way of sizing a text field. Better to specify a number of columns (roughly translates to # of characters) when it is being constructed, put it in a row of it’s own (spanning 3 cell widths), and not specify it to fill that row.

Advertisement