[英]java Jbutton array preventing constructor from finishing running
所以我想创建一个程序,用8个JButton创建一个JPanel窗口。 我没有重复JButton,而是使用所有JButton制作了一个数组,并进行了循环以创建它们。 但是,自从我创建数组以来,构造函数将在循环结束后继续进行。 直到我将JButton制成数组,这才发生。
public class Gui extends JFrame {
private JButton Subject[] = new JButton[7];
private String SubjNames[] = {"Length", "Mass", "Currency", "Temperature", "Time", "Speed", "Data", "Cooking"};
private int SubjectLocX = 40;
private int SubjectLocY = 50;
public Gui (){
super("Converter");
setLayout(null);
System.out.println("yes");
for (int i = 0; i<8; i++) {
Subject[i] = new JButton(SubjNames[i]);
Subject[i].setLocation(SubjectLocX,SubjectLocY);
Subject[i].setSize(200,50);
add(Subject[i]);
if (i < 3) {
SubjectLocX = 40;
SubjectLocY += 100;
} else if (i == 3) {
SubjectLocY = 50;
} else if (i > 3) {
SubjectLocX = 330;
SubjectLocY += 100;
}
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,500);
setLocation(400,200);
setVisible(true);
}
}
是的,我导入了所需的所有内容,并在单独的类中创建了该类的对象。 它会运行,但是构造函数在循环后将不会继续。 如果删除数组为“ Subject [i]”的行,则构造函数将完成并显示窗口,但数组为空,则不会。 为什么??
可能是因为您有一个包含7个元素的JButton数组,并且正在尝试初始化其中的8个元素。 使用private JButton Subject[] = new JButton[8]
更改声明,您将修复。
您的代码对我来说是workinf,您在“ for”循环中只有一个数组超出范围,条件必须是for (int i = 0; i<7; i++)
但其他所有方法都有效,请记住调用“ new Gui().setVisible(true);
“
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.