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

时间:2014-10-10 01:52:46

标签: java swing layout-manager gridbaglayout

我制作了5个简单的按钮,看看GridBagLayout约束是如何工作的,并让它们像十字架一样设置。我试图尝试北方的网格宽度,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);

1 个答案:

答案 0 :(得分:4)

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

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);

这意味着所有其他控件的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);

现在,我可能错了,但你似乎试图让北方按钮控制整个上排,就像...

Fill

你需要像......那样的东西。

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);

同样......