我正在使用GridBagLayout编写地址簿GUI,但问题是当我设置gridx和gridy时,它似乎没有使用布局,组件会掉落在框架的中心。我只贴了一小段代码来展示一个JButton,以便让您看到发生了什么。请查看代码并指导我如何修复它。目前按钮位于JFrame的中心。由于我只是初学者,请不要介意我的愚蠢代码风格或任何类似的问题。
public class rect
{
JFrame frame ;
JPanel panel1 ;
JButton b1;
GridBagConstraints gbc;
public rect()
{
panel1 = new JPanel();
panel1.setSize(300,300);
panel1.setLayout(new GridBagLayout());
gbc = new GridBagConstraints();
frame= new JFrame("Address ?ooK ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
b1= new JButton () ;
b1.setText("Hello ");
gbc.gridx=1;
gbc.gridy=0;
panel1.add(b1, gbc) ;
frame.add(panel1);
panel1.setVisible(true);
frame.setVisible(true);
}
weightx/weight
设置为1.0
并将anchor
更改为GridBagLayout.NORTH
... 然后看看会发生什么;-) 我建议仔细阅读 GBL 文档和教程。 - Guillaume Polet