无法跨越和左对齐 GridBagLayout 中的文本字段

问题描述

我有这个代码

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,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,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);
        c.gridx = x;
        c.gridy = y;
        return c;
    }
}

它创建:

enter image description here

但我需要文本字段始终跨越 2 列并且所有内容都要左对齐:

enter image description here

我该怎么做?

解决方法

c.gridwidth = 3;

必须:

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

结果:

enter image description here

编辑

顺便说一句。 “跨越两个单元格”似乎是一种完全随意调整文本字段大小的方法。最好在构建时指定多列(大致转换为字符数),将其放在自己的一行中(跨越 3 个单元格宽度),不要指定它来填充行。