我如何让事件处理程序跟踪用户点击它的次数?

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

我对我在这里做错了什么有点困惑。用户获得 3 卷,我正在尝试使用计数器来确定他们单击 JavaFX 按钮的次数。当我在事件处理程序之前初始化 diceRollCounter 时,出现错误。如果我在事件处理程序中初始化 diceRollCounter,每次单击按钮时我都会将 diceRollCounter 重置回零,这违背了它的目的。

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

问题是您无法通过事件更改局部变量。试试这个:

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

这是一个article about the issue you encountered

关于anonymous classes的解释(我写new EventHandler<>() {...}的地方)。