Java GridBagConstraints gridx and gridy not working?(Java GridBagConstraints gridx 和 gridy 不起作用?)
问题描述
我正在尝试使用 gridx
和 gridy
约束来定位我的按钮.但他们不工作!如果我更改 gridx
和 gridy
变量,什么也不会发生.如果我将 GridBagConstraints
的填充更改为 NONE
,它仍然不起作用.
I am trying to use the gridx
and gridy
constraints to position my button. But they do not work! If I change the gridx
and gridy
variables, nothing happens. If I change the fill to GridBagConstraints
to NONE
, it still does not work.
我错过了什么吗?
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);
}
}
如果这很难阅读,问题就出在这里:
If that is hard to read, here is where the problem lies:
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 layout了,难道gridX和gridY不是只有在你的JPanel中有多个JComponent的时候才有效果吗?看来你只有一个 JButton,所以 GridBagLayout 没有任何布局可做.
It's been a while since I've done swing layouts, but don't gridX and gridY only have effects if you have more than one JComponent in your JPanel? It seems you only have a JButton, so the GridBagLayout doesn't have any layout to do.
这篇关于Java GridBagConstraints gridx 和 gridy 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java GridBagConstraints gridx 和 gridy 不起作用?
基础教程推荐
- 在螺旋中写一个字符串 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01