java Jbutton 数组阻止构造函数完成 运行
java Jbutton array preventing constructor from finishing running
所以我想创建一个程序来创建一个带有 8 个 JButton 的 JPanel window。我没有重复 JButtons,而是用所有 JButtons 创建了一个数组并创建了一个循环来创建它们。然而,自从我制作了一个数组后,构造函数将不会在循环完成后继续进行。在我将 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);
}
}
是的,我导入了所有需要的东西,并在单独的 class 中创建了 class 的对象。它将运行,但构造函数不会在循环后继续。如果删除带有数组 "Subject[i]" 的行,则构造函数完成并出现 window,但对于数组,则不会。为什么??
可能是因为您有一个包含 7 个元素的 JButton 数组,而您正试图初始化其中的 8 个。使用 private JButton Subject[] = new JButton[8]
更改声明,您将修复。
你的代码对我有用,你只是在 "for" 循环中有一个数组越界,条件必须是 for (int i = 0; i<7; i++)
但其他一切都有效,记得调用“new Gui().setVisible(true);
"
所以我想创建一个程序来创建一个带有 8 个 JButton 的 JPanel window。我没有重复 JButtons,而是用所有 JButtons 创建了一个数组并创建了一个循环来创建它们。然而,自从我制作了一个数组后,构造函数将不会在循环完成后继续进行。在我将 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);
}
}
是的,我导入了所有需要的东西,并在单独的 class 中创建了 class 的对象。它将运行,但构造函数不会在循环后继续。如果删除带有数组 "Subject[i]" 的行,则构造函数完成并出现 window,但对于数组,则不会。为什么??
可能是因为您有一个包含 7 个元素的 JButton 数组,而您正试图初始化其中的 8 个。使用 private JButton Subject[] = new JButton[8]
更改声明,您将修复。
你的代码对我有用,你只是在 "for" 循环中有一个数组越界,条件必须是 for (int i = 0; i<7; i++)
但其他一切都有效,记得调用“new Gui().setVisible(true);
"