Java GridBagConstraints gridx和gridy无法正常工作?

我试图使用gridxgridy约束来定位我的按钮。 但他们不工作! 如果我更改gridxgridy变量,则没有任何反应。 如果我将填充更改为GridBagConstraintsNONE ,它仍然无效。

我在这里错过了什么吗?

 import java.awt.*; import javax.swing.*; public class Window extends JFrame{ private static final long serialVersionUID = 1L; JFrame frame = new JFrame("GUI"); JTextField username = new JTextField(20); public void CreateWindow(){ JPanel pane = new JPanel(); pane.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.NONE; JButton button = new JButton("Button 1"); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 3; //Has no effect c.gridy = 5; //Has no effect c.anchor = GridBagConstraints.NORTHWEST;//If I remove this, it still does not work. pane.add(button, c); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.setSize(400, 600); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.add(pane); frame.setVisible(true); } } 

如果这很难理解,问题出在哪里:

 JPanel pane = new JPanel(); pane.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.NONE; JButton button = new JButton("Button 1"); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 3; //Has no effect c.gridy = 5; //Has no effect c.anchor = GridBagConstraints.NORTHWEST; //If I remove this, it still does not work. pane.add(button, c); 

自从我完成了swing布局以来已经有一段时间了,但是如果你的JPanel中有多个JComponent,那么gridX和gridY是否只有效果? 看起来你只有一个JButton,所以GridBagLayout没有任何布局要做。