java - 如何使用 GridBagConstraints setRows 和 setColumns?

标签 java swing layout-manager gridbaglayout

如何使用 setRows 和 setColumns 更改窗口中的行数和列数?

这是我的代码副本以及我尝试实现设置的行和列的位置:

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.*;
@SuppressWarnings("unused")

public class GUI
{

    public static void main(String[] args)
    {
        new GUI();
    }


    public GUI()
    {

        JFrame AG = new JFrame("Adventure Game");
        AG.setExtendedState(JFrame.MAXIMIZED_BOTH);
        AG.setResizable(true);
        AG.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel p=new JPanel();

        p.setLayout (new GridBagLayout());

        AG.add(p);
        GridBagConstraints GBC = new GridBagConstraints();
        GridLayout.setRows(100);//heres the set rows<<<<<<<<<<<<<<<<<<<
        GridLayout.setColumns(100);//heres the set columns<<<<<<<<<<<<<<<<<<<
        AG.getContentPane().add(p, BorderLayout.NORTH);


        JButton saveButton =new JButton("Save");
        JButton loadButton =new JButton("Load");
        JButton optionsButton = new JButton("Options");

        JLabel textBox= new JLabel("Story line will go here.");

        JLabel label11 = new JLabel("Test 1");
        GBC.gridx = 0;
        GBC.gridy = 1;

        p.add(label11,GBC);
        JLabel label12 = new JLabel("Test 2");
        GBC.gridx = 0;
        GBC.gridy = 2;
        p.add(label12,GBC);
        JLabel label13 = new JLabel("Test 3");
        GBC.gridx = 0;
        GBC.gridy = 3;
        p.add(label13,GBC);
        JLabel label14 = new JLabel("Test 4");
        GBC.gridx = 0;
        GBC.gridy = 5;
        p.add(label14,GBC);

        AG.setVisible(true);
    }
}

最佳答案

GridBagConstraints 使用 GridBagLayout,而不是 GridLayout。您对 GridLayout 的调用不会执行任何操作。

要使用 GridBagConstraints 设置行和列,您需要使用 GBC.gridx = ...;GBC.gridy = ...;

关于java - 如何使用 GridBagConstraints setRows 和 setColumns?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27063925/

相关文章:

java - 如何指定 Jackson 仅使用字段 - 最好是全局的

java - 如何使用 GridBagLayout 在多列上拉伸(stretch)组件?

java - 在 Java 1.6 中,为什么使用默认的 add() 将一个 Jpanel 添加到另一个 JPanel 不显示添加的面板?

java - 如何在 JFrame 中将 FlowLayout 更改为 BoxLayout

java - wsimport from https : [ERROR] java. security.cert.CertificateException:不存在主题备用名称

java - 确定数组中特定元素的总和

java - Spring Mongo 条件查询两次相同的字段

java - 灵活的 Swing 输入对话框

java - JComboBox 返回值

java - 在 GUI、java 上使用 Glue