【问题标题】:How do I get event handler to keep track of how many times the user clicked it?如何让事件处理程序跟踪用户单击它的次数?
【发布时间】:2021-09-16 17:31:15
【问题描述】:

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

【问题讨论】:

  • 使diceRollCounter 成为类的成员而不是局部变量。

标签: java button javafx counter


【解决方案1】:

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

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&lt;&gt;() {...})。

【讨论】:

  • 请注意,如果您将 diceRollCounter 设为周围类中的实例变量(而不是 OP 中的局部变量),您仍然可以使用 lambda 表达式而不是匿名内部类。
  • 我不想对周围类的实例变量执行此操作,因为这样您每个实例只能运行一次此代码。 (如果是静态的,则每个类一次)
  • 因为每个实例只能运行此代码一次,并且处理程序驻留在 ... 实例按钮上;)或更直接地说:这不是一个很好的论点。已经建议使用实例变量(如@James_D 和@Abra)正在走向合理的解决方案 - 更好的是拥有一个真正的“游戏模型”,它携带到计数器(以及访问它的 api)并让处理程序更新它并查询允许的模型:) 处理程序不是决定业务/游戏逻辑的地方。
  • 你说得对,我这样写还有另一个原因,而且它更容易解释:只需复制和粘贴
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-21
  • 1970-01-01
  • 2015-12-22
  • 1970-01-01
  • 1970-01-01
  • 2015-01-17
  • 1970-01-01
相关资源
最近更新 更多