首页 > 解决方案 > 由 JButton 组成的 ArrayList。但没有按预期工作

问题描述

我现在正在进行一个项目,我正在尝试一些新代码以使我的程序更有效率。我在想一个ArrayList“骰子”,它将包含一些按钮(应该是骰子)。例如array.add(die1),如果我假设我可以引用数组中的对象而不是实际的按钮。

例如:我可以设置 die1 的文本,因为die1.setText("");我也想直接对数组中的对象进行设置,这样我就可以使用循环,比如,array.get(i).setText("");

但它不起作用,这很奇怪。如果我这样做array.get(0).getClass(),它会说javax.Swing.JButton这似乎是正确的。

爪哇 11

ArrayList dice = new ArrayList<JButton>();


private void die1ActionPerformed(java.awt.event.ActionEvent evt) {                                     
    // TODO add your handling code here:
    if (die1.getBackground() == Color.red) {

        dice.remove(dice.indexOf(die1));
        die1.setBackground(Color.green);
    }
    else {
        dice.add(die1);
        die1.setBackground(Color.red);            
    }
}     

private void btnRollActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:

    for (int i = 0; i < dice.size(); i++) {

        int random = roll();

        dice.get(i).setText(""+random); //This displays as error; uncompilable

    }
}      

预期:工作。但自然它无法编译并崩溃。

标签: javaswingarraylistnetbeansjbutton

解决方案


因为你还没有输入你的列表的声明。

尝试这个:

List<JButton> dice = new ArrayList<>();

推荐阅读