gridwidth 和 gridheight 如何工作(Java guid GridBagLayout)?

Joh*_*ado 2 java swing layout-manager gridbaglayout

我制作了 5 个简单的按钮来查看 GridBagLayout 约束是如何工作的,并将它们设置成十字形。我尝试尝试北方的 gridwidth,gbc.gridwidth = 2; (因为默认值是 0,所以 1 和 2,它们是 3 列)准确地说。难道它不应该在 North 按钮所在位置的 x 轴上占据 3 列吗?但是当你运行它时,按钮会全部重叠。请帮忙解释一下是什么问题?谢谢

    JPanel jp = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();

    JButton jb1 = new JButton("North");
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridwidth = 2; //Here, it won't take up three columns just at the top where it sits
    jp.add(jb1, gbc);

    JButton jb2 = new JButton("West");
    gbc.gridx = 0;
    gbc.gridy = 1;
    jp.add(jb2, gbc);

    JButton jb3 = new JButton("Center ");
    gbc.gridx = 1;
    gbc.gridy = 1;
    jp.add(jb3, gbc);

    JButton jb4 = new JButton("East");
    gbc.gridx = 2;
    gbc.gridy = 1;
    jp.add(jb4, gbc);

    JButton jb5 = new JButton("South");
    gbc.gridx = 1;
    gbc.gridy = 2;
    jp.add(jb5, gbc);

    add(jp);

    setVisible(true);
Run Code Online (Sandbox Code Playgroud)

Mad*_*mer 5

核心问题是,您还没有重置约束...

JButton jb1 = new JButton("North");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2; //Here, it won't take up three columns just at the top where it sits
jp.add(jb1, gbc);

JButton jb2 = new JButton("West");
// Still using the gridwidth value from before...
gbc.gridx = 0;
gbc.gridy = 1;
jp.add(jb2, gbc);
Run Code Online (Sandbox Code Playgroud)

这意味着所有其他控件的值gridwidth仍然设置2为...

添加gbc = new GridBagConstraints();后尝试添加jb1

此外,由于某种原因,gridwidth它不是零索引,它从 开始1,所以你可能想3改用......

JButton jb1 = new JButton("North");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 3; //Here, it won't take up three columns just at the top where it sits
jp.add(jb1, gbc);

gbc = new GridBagConstraints();
JButton jb2 = new JButton("West");
gbc.gridx = 0;
gbc.gridy = 1;
jp.add(jb2, gbc);
Run Code Online (Sandbox Code Playgroud)

现在,我可能是错的,但你似乎试图让北按钮控制整个上排,比如......

填

为此,你需要像......

JButton jb1 = new JButton("North");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 3; //Here, it won't take up three columns just at the top where it sits
gbc.fill = GridBagConstraints.HORIZONTAL;
jp.add(jb1, gbc);
Run Code Online (Sandbox Code Playgroud)

还有...