【问题标题】:java Jbutton array preventing constructor from finishing runningjava Jbutton数组阻止构造函数完成运行
【发布时间】:2016-04-25 21:02:44
【问题描述】:

所以我想创建一个程序来创建一个带有 8 个 JButton 的 JPanel 窗口。我没有重复 JButton,而是用所有 JButton 创建了一个数组,并创建了一个循环来创建它们。然而,自从我创建了一个数组后,构造函数在循环完成后将不会继续。直到我将 JButtons 变成一个数组,这种情况才发生。

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]”的行,则构造函数完成并出现窗口,但对于数组,它不会。为什么??

【问题讨论】:

  • 请记住,当您将数组声明为 new JButton[7] 时,意味着您只分配了 7 个元素

标签: java arrays jpanel jbutton


【解决方案1】:

可能是因为您有一个包含 7 个元素的 JButton 数组,并且您正在尝试初始化其中的 8 个元素。使用private JButton Subject[] = new JButton[8] 更改声明,您将修复。

【讨论】:

    【解决方案2】:

    您的代码对我来说是有效的,您只是在“for”循环中有一个超出范围的数组,条件必须是for (int i = 0; i&lt;7; i++),但其他一切正常,记得调用“new Gui().setVisible(true);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-30
      相关资源
      最近更新 更多