我做了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);
最佳答案
核心问题是,您尚未重置约束...
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);
现在,我可能是错的,但是您似乎正在尝试使向北按钮控制整个上一行,例如...
为此,您需要类似...
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);
还有...