如何在Java Swing GridLayout中修复错误,GridBagConstraints

问题描述 投票:0回答:1

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

我需要将元素放置在混凝土单元格上,但是它们放置了错误的(picture)

如何使用GridLayout将元素放置到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;
    }
}

java swing layout-manager
1个回答
0
投票

GridBagConstraints用于Grid Bag Layout,而不是Grid Layout

© www.soinside.com 2019 - 2024. All rights reserved.