0

In the following code, the setText() function is giving an error, not allowing the text to be changed for JLabel a and JLabel b. What is the fix?

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);
        }
    }
}

Initializations:

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);
    }
}
SapuSeven
  • 1,473
  • 17
  • 30

1 Answers1

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);
    }

    ...
}

In your constructor, you are creating 2 new label variables, and you are initializing those variables instead of your field variables.

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

This will fix your problem. Remove the declarations in your constructor, and initialize the field labels.

Vince
  • 14,470
  • 7
  • 39
  • 84