如何修复 GridLayout/GridBagConstraints 中的错误?

How to fix error in GridLayout/GridBagConstraints?

为什么 GridLayot 无法在 Swing 中工作 Java?

我需要将元素放置在具体单元格中,但他们放置错误 (picture)

如何在 Java 使用网格布局的 Swing 中将元素放置到具体单元格中?

我的代码:

package com.KvaksManYT;

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

public class GUI extends JFrame {
    public GUI() {
        super("Test");
        setBounds(100, 100, 250, 100);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Container container = this.getContentPane();
        container.setLayout(new GridLayout(3, 2, 2, 2));
        container.add(but1, onPosition(1, 2));
        container.add(but2, onPosition(2, 2));
        container.add(but3, onPosition(1, 1));
        container.add(but4, onPosition(2, 1));
    }

    private JButton but1 = new JButton("Press 1");
    private JButton but2 = new JButton("Press 2");
    private JButton but3 = new JButton("Press 3");
    private JButton but4 = new JButton("Press 4");

    private GridBagConstraints onPosition(int x, int y) {
        GridBagConstraints layConstraints = new GridBagConstraints();
        layConstraints.fill = GridBagConstraints.BOTH;
        layConstraints.gridx = x;
        layConstraints.gridy = y;
        return layConstraints;
    }
}

GridBagConstraints用于Grid Bag Layout, rather than Grid Layout

您必须从 0 开始数到:

public class GUI extends JFrame {
    public GUI() {
        super("Test");
        setBounds(100, 100, 250, 100);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        GridBagConstraints layConstraints = new GridBagConstraints();
        layConstraints.fill  = GridBagConstraints.NONE;
        layConstraints.insets = new Insets(3, 2, 2, 2);

        Container container = this.getContentPane();
        container.setLayout(new GridBagLayout());

        container.add(but1, onPosition(0, 1, layConstraints));
        container.add(but2, onPosition(1, 1, layConstraints));
        container.add(but3, onPosition(0, 0, layConstraints));
        container.add(but4, onPosition(1, 0, layConstraints));

    }