java—如何让事件处理程序跟踪用户单击它的次数?

58wvjzkj  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(341)

我有点困惑我在这里做错了什么。用户得到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);
    }
});
wdebmtf2

wdebmtf21#

问题是,您无法使用事件更改局部变量。尝试使用以下方法:

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

下面是一篇关于您遇到的问题的文章。
关于匿名类的解释(我在那里写的 new EventHandler<>() {...} ).

相关问题