【发布时间】:2012-01-14 03:23:00
【问题描述】:
我正在尝试使用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);
【问题讨论】:
-
._. gridx 和 gridy 不影响按钮。你甚至读过这个问题吗?
-
@Ken,您能给我们提供所需布局的可视化表示吗?也许那时我们可以建议不同的(更合适的)布局管理器......
-
gridx和gridy不改变按钮位置。
标签: java swing awt jframe jpanel