我正在尝试使用gridx
和gridy
约束来定位我的按钮。但是它们不起作用!如果更改gridx
和gridy
变量,则什么也不会发生。如果我将填充从GridBagConstraints
更改为NONE
,它仍然不起作用。
我在这里想念什么吗?
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);
最佳答案
自从我完成了挥杆布局以来已经有一段时间了,但是如果您的JPanel中有多个JComponent,则gridX和gridY不会仅具有效果吗?看来您只有一个JButton,所以GridBagLayout没有任何布局。