如何在 Java 中使用两个参数创建 ObservableBooleanValue?

How to make ObservableBooleanValue with two arguments in Java?

我想在 ObservableBooleanValue 的 when() 条件中添加第二个参数。如果只有一个参数 它工作正常。该行的问题:

game.winnerProperty().isEqualTo(Square.State.EMPTY) || (GameTimer::isTimeOver==true)

没关系:

game.winnerProperty().isEqualTo(Square.State.EMPTY) //This is BooleanBinding

代码:

playerLabel.textProperty().bind(
    Bindings.when(
        game.gameOverProperty().not()
    )
        .then("Actual Player: ")
        .otherwise(
            Bindings.when(
                game.winnerProperty().isEqualTo(Square.State.EMPTY) || (GameTimer::isTimeOver==true)
            )
                .then("Draw")
                .otherwise("Winner: ")
        )
);

如何添加第二个布尔类型的参数?

你可以做到

game.winnerProperty().isEqualTo(Square.State.EMPTY).or(/* whatever you actually mean here */);

此处 or 的参数需要是另一个 ObservableBooleanValue(例如 BooleanProperty):我真的不知道您当前拥有的方法引用的目的是什么。

有时合并多个绑定会很方便。

然而,这可能会导致难以 understand/maintain 的复杂代码。使用 Bindings.createStringBinding 并添加适当的依赖项会更容易:

playerLabel.textProperty().bind(
    Bindings.createStringBinding(() -> {
            if (game.isGameOver()) {
                 return Square.State.EMPTY.equals(game.getWinner()) || gameTimer.isTimeOver()
                              ? "Draw"
                              : "Winner: ";
            } else {
                 return "Actual Player: ";
            }
        },
        game.gameOverProperty(),
        game.winnerProperty(),
        gameTimer.timeOverProperty()));