JLabel.setText()不起作用

时间:2014-04-30 20:08:07

标签: java user-interface runtime-error actionlistener jlabel

在以下代码中,setText()函数发出错误,不允许更改JLabel aJLabel b的文本。有什么问题?

public void actionPerformed(ActionEvent e) {
    boolean is1 = true;
    if (e.getActionCommand().equals("r")) {
        if (is1 == true) {
            r1++;
            a.setText("Dice Rolls: " + r1);
        } else {
            r2++;
            b.setText("Dice Rolls: " + r2);
        }
    }
}

初​​始化:

public class Clacker implements ActionListener {
    JLabel a;
    JLabel b;
    int r1 = 0;
    int r2 = 0;
    ...
    public Clacker() {
        JLabel a=new JLabel("Dice Rolls: " + r1);
        JLabel b=new JLabel("Dice Rolls: " + r2);
    }
}

1 个答案:

答案 0 :(得分:1)

public class Clacker implements ActionListener {
    JLabel a;
    JLabel b;
    int r1=0;
    int r2=0;

    public Clacker(){
        JLabel a=new JLabel("Dice Rolls: "+r1);
        JLabel b=new JLabel("Dice Rolls: "+r2);
    }

    ...
}

在构造函数中,您将创建2个新的标签变量,并且正在初始化这些变量而不是字段变量。

   public Clacker(){
       a=new JLabel("Dice Rolls: "+r1);
       b=new JLabel("Dice Rolls: "+r2);
   }

这将解决您的问题。删除构造函数中的声明,并初始化字段标签。

相关问题