java - 为什么 JButton btn[3][5] 没有被放置在 setBounds() 调用中给定的位置上?
问题描述
我正在编写一个程序,它应该包含多个彼此相邻设置的 JButton。起初我想要一个 4 x 6 网格。我有 3 个类:一个包含 main 方法的 Main 类和 Gui 类构造函数的构造函数调用。Gui 类应该包括所有 JObjects (JButtons) + JFrame 设置。然后是第三个 ButtonPlacement 类,其中包括 setBounds 方法调用。当我在 Eclipse 中运行代码时,我的 Button Array 中的每个 Button 都放置在正确的位置,除了最后一个:btn[3][5]。它和整个 JFrame 一样大。
主类:
package pack1;
public class Main {
public static void main(String[] args) {
new Gui();
}
}
桂班:
package pack1;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import pack1.ActionHandler;
import pack1.ButtonPlacement;
public class Gui {
static JFrame jf;
static JButton btn[][] = new JButton[4][6];
JButton btnReset;
public Gui() {
jf = new JFrame();
jf.setSize(500, 600);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setResizable(false);
jf.setLocationRelativeTo(null);
for(int i = 0; i<4;++i) {
for(int j = 0; j<6; ++j) {
btn[i][j] = new JButton("btn" + i + j);
btn[i][j].setVisible(true);
btn[i][j].addActionListener(new ActionHandler());
btn[i][j].setFocusPainted(false);
btn[i][j].setContentAreaFilled(true);
btn[i][j].setBorder(null);
btn[i][j].setFont(new Font("Century Gothic", Font.PLAIN, 20));
jf.add(btn[i][j]);
}
}
ButtonPlacement.place();
jf.setVisible(true);
}
}
类按钮放置:
package pack1;
import pack1.Gui;
public class ButtonPlacement {
public static void place() {
Gui.btn[0][0].setBounds(0, 140, 100, 60);
Gui.btn[1][0].setBounds(100, 140, 100, 60);
Gui.btn[2][0].setBounds(200, 140, 100, 60);
Gui.btn[3][0].setBounds(300, 140, 100, 60);
Gui.btn[0][1].setBounds(0, 200, 100, 60);
Gui.btn[1][1].setBounds(100, 200, 100, 60);
Gui.btn[2][1].setBounds(200, 200, 100, 60);
Gui.btn[3][1].setBounds(300, 200, 100, 60);
Gui.btn[0][2].setBounds(0, 260, 100, 60);
Gui.btn[1][2].setBounds(100, 260, 100, 60);
Gui.btn[2][2].setBounds(200, 260, 100, 60);
Gui.btn[3][2].setBounds(300, 260, 100, 60);
Gui.btn[0][3].setBounds(0, 320, 100, 60);
Gui.btn[1][3].setBounds(100, 320, 100, 60);
Gui.btn[2][3].setBounds(200, 320, 100, 60);
Gui.btn[3][3].setBounds(300, 320, 100, 60);
Gui.btn[0][4].setBounds(0, 380, 100, 60);
Gui.btn[1][4].setBounds(100, 380, 100, 60);
Gui.btn[2][4].setBounds(200, 380, 100, 60);
Gui.btn[3][4].setBounds(300, 380, 100, 60);
Gui.btn[0][5].setBounds(0, 440, 100, 60);
Gui.btn[1][5].setBounds(100, 440, 100, 60);
Gui.btn[2][5].setBounds(200, 440, 100, 60);
Gui.btn[3][5].setBounds(300, 440, 100, 60);
}
}
我希望按钮 btn[3][5] 位于其位置 300、440,其大小为 100、60,但按钮与 JFrame 一样大。
解决方案
将此添加到 Gui 类中,让它对我正常工作:
jf.setLayout(null);
推荐阅读
- html - 选择父母和孩子以找到跨度
- sql - 简单解析后扩展 tsquery
- spring-boot - 没有为 id "null" 映射 PasswordEncoder
- python - 有没有办法在 pdf 中搜索特定关键字并显示与该关键字关联的值?
- bash - 如何用自然数替换文本每一行中相同位置的字符?
- c++ - 避免在函数调用中计算数组元素
- amazon-web-services - AWS Cloudformation 创建的角色未显示在身份池下拉列表中
- nmake - 计算的宏名称
- php - 当我设置配置数据库时,它正在重置我的数据库连接
- c - 如何在 0 和 max 之间生成随机双精度(在 C 中)?