我最近被介绍给 GridBagLayout 来替代 vanilla JPanel 布局,但是我在使用 gridwidth/height 和 gridx/y 等函数时遇到了麻烦。我不确定它们在更改 GUI 的大小和按钮的位置方面是如何工作的。下面是我的教授给我的代码供我参考,我试着摆弄某些数字,但结果从来没有像我预期的那样发生,我不知道为什么。
编辑 1:为了澄清,我想知道 gridwidth、gridheight、gridx 和 gridy 函数是如何调整 GUI 大小和定位按钮位置的。
import java.awt.*;
import javax.swing.*;
class Bar1 {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c.gridx=0;
c.gridy=0;
c.gridwidth=2;
c.gridheight=1;
c.weightx = 2;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
JButton b = new JButton("Hello");
panel.add(b, c);
c.gridx=0;
c.gridy=1;
c.gridwidth=1;
c.gridheight=1;
JButton b2 = new JButton("World");
panel.add(b2, c);
c.gridx=1;
c.gridy=1;
c.gridwidth=1;
c.gridheight=1;
JButton b3 = new JButton("!!!");
panel.add(b3, c);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}