如何设置网格布局中按钮的位置?
我的代码:
public class Form {
public static void main(String[] args) {
Form form = new Form();
form.go();
}
public void go() {
JFrame form = new JFrame();
GridLayout layout = new GridLayout(2,7);
Label nameLabel = new Label("Name");
form.setLayout(layout);
JTextField nameBox = new JTextField();
form.getContentPane().add(nameLabel);
form.getContentPane().add(nameBox);
form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
form.setSize(500,500);
form.setVisible(true);
}
}
现在,我如何设置 JTextField 的位置,使其为 2,7 而不是 1,2?
My code:
public class Form {
public static void main(String[] args) {
Form form = new Form();
form.go();
}
public void go() {
JFrame form = new JFrame();
GridLayout layout = new GridLayout(2,7);
Label nameLabel = new Label("Name");
form.setLayout(layout);
JTextField nameBox = new JTextField();
form.getContentPane().add(nameLabel);
form.getContentPane().add(nameBox);
form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
form.setSize(500,500);
form.setVisible(true);
}
}
Now, how can I set this position of the JTextField so its 2,7 and not 1,2?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
GridLayout 总是按照容器中的组件在容器中的顺序对它们进行排序。您不能将组件放置在特定位置,除非为之前的所有位置插入虚拟组件。
您可能想尝试其他布局管理器。 GridBagLayout 可以做到这一点,但使用起来相当复杂。
A GridLayout will always sort the components of the container in the order they are in the container. You can't put a component at a specific place, other than by inserting dummy components for all the places before.
You might want to try other layout managers. GridBagLayout can do this, but is quite more complicated to use.
尝试将空组件添加到 2,7 之前的位置,例如:
Try adding empty components into the positions before 2,7 , something like:
似乎你最好使用 GridBag 布局,并使用 gridx 网格约束来定位你的组件...这是来自 java 的教程: http://download.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
据我所知,你不能使用网格布局直接将组件放置在任何你想要的地方(@Paŭlo Ebermann 也提到过同样的事情)
seems that you better use GridBag layout,and use gridx gridy constraints to position your components...Here is a tutorial from java: http://download.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
As far as I know you cannot directly put components wherever you want using grid layout( @Paŭlo Ebermann has mentioned the same thing)