我发现有很多关于如何使用GridBagLayout的文章,但是它们总是与我所需要的相反。
例如,在this post中,按钮的第一行跨越宽度,而在其下方仅一个按钮。我的兴趣主要是前两行。
但是考虑相反的情况,我希望第1行中的正好1个按钮跨过第2行中的正好4个按钮的宽度,并且此后可以是任意多个。
[=========按钮========] [=========按钮========]
[按钮] [按钮] [按钮] [按钮]
[按钮] [按钮] [按钮] [按钮]
最佳答案
这是您如何获得所需布局的方法。
public GridBagConstraintsFrame() {
Container c = getContentPane();
JPanel p = new JPanel(new GridBagLayout());
c.setLayout(new BorderLayout());
{
JButton button1 = new JButton("Button 1");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = 1;
gbc.gridwidth = 4;
gbc.weightx = 0;
gbc.weighty = 0;
gbc.fill = gbc.HORIZONTAL;
p.add(button1, gbc);
}
{
JButton button2 = new JButton("Button 2");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 4;
gbc.gridy = 0;
gbc.gridheight = 1;
gbc.gridwidth = 4;
gbc.weightx = 0;
gbc.weighty = 0;
gbc.fill = gbc.HORIZONTAL;
p.add(button2, gbc);
}
{
JButton button3 = new JButton("Button 3");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 0;
gbc.weighty = 0;
p.add(button3, gbc);
}
{
JButton button3 = new JButton("Button 4");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 0;
gbc.weighty = 0;
p.add(button3, gbc);
}
{
JButton button3 = new JButton("Button 5");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 1;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 0;
gbc.weighty = 0;
p.add(button3, gbc);
}
{
JButton button3 = new JButton("Button 6");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 3;
gbc.gridy = 1;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 0;
gbc.weighty = 0;
p.add(button3, gbc);
}
{
JButton button3 = new JButton("Button 7");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 4;
gbc.gridy = 1;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 0;
gbc.weighty = 0;
p.add(button3, gbc);
}
{
JButton button3 = new JButton("Button 8");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 5;
gbc.gridy = 1;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 0;
gbc.weighty = 0;
p.add(button3, gbc);
}
{
JButton button3 = new JButton("Button 9");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 6;
gbc.gridy = 1;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 0;
gbc.weighty = 0;
p.add(button3, gbc);
}
{
JButton button3 = new JButton("Button 10");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 7;
gbc.gridy = 1;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 0;
gbc.weighty = 0;
p.add(button3, gbc);
}
c.add(p, BorderLayout.CENTER);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Gridbag constraints.");
pack();
setVisible(true);
}
这是它的外观。
如果您需要解释,请在注释中告诉我,我将尝试解释每段代码。
PS。这是一个JFrame。
关于java - Java GridBagLayout和GridBagConstraints,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28084409/