Search code examples
javabuttonjavafxcounter

How do I get event handler to keep track of how many times the user clicked it?


I am a little confused as to what I am doing wrong here. The user gets 3 rolls and I am trying to use a counter to determine how many times they have clicked the JavaFX button. When I initialize the diceRollCounter before the event handler I get an error. and if I initialize the diceRollCounter within the event handler, I get the diceRollCounter resetting back to zero every time the button is clicked, which defeats its purpose.

int diceRollCounter = 0;

rollDice.setOnAction(e-> {
    if (diceRollCounter < 3) {
        cup.shakeCup();
        diceRollCounter++;
    } else if (diceRollCounter > 3) {
        Text noMoreRolls = new Text();
        noMoreRolls.setText("You are out of rolls for this round");
        noMoreRolls.setX(355);
        noMoreRolls.setY(525);
        root.getChildren().add(noMoreRolls);
    }
});

Solution

  • The problem is that you can't change a local variable with an event. Try using this:

    rollDice.setOnAction(new EventHandler<>() {
        int diceRollCounter = 0;
    
        public void handle(ActionEvent e) {
            if (diceRollCounter < 3) {
                cup.shakeCup();
                diceRollCounter++;
            } else if (diceRollCounter > 3) {
                Text noMoreRolls = new Text();
                noMoreRolls.setText("You are out of rolls for this round");
                noMoreRolls.setX(355);
                noMoreRolls.setY(525);
                root.getChildren().add(noMoreRolls);
            }
        }
    });
    

    Here is an article about the issue you encountered.

    An explanation about anonymous classes (where I wrote new EventHandler<>() {...}).