JavaFX 8 Bindings.when 和 Bindings.divide 创建除以零

Rob*_*t K 3 java javafx-8

我正在为 Bindings.when 苦苦挣扎...我试图创建一个百分比分数,当成功测试的数量发生变化(在下面的代码中反映为“successCountProperty”)或测试总数发生变化时(反映在“结果”的 sizeProperty 中)。当我执行这段代码时,我得到 java.lang.ArithmeticException: / 为零。当我最初遇到异常时,我找到了 Bindings.when().then().otherwise(),在我的脑海中应该可以解决问题。不幸的是,在执行此代码时,尽管 'when' 返回 false,'then' 仍在执行。任何人都可以帮忙吗?

public void foo()
{
    DoubleProperty scoreProperty = new SimpleDoubleProperty(0);
    ListProperty<String> results = new SimpleListProperty<>(FXCollections.observableArrayList());

    IntegerProperty successCountProperty = new SimpleIntegerProperty(0);

    scoreProperty.bind(Bindings.when(results.sizeProperty().greaterThan(0))
            .then(Bindings.divide(successCountProperty, results.sizeProperty())).otherwise(0));
}
Run Code Online (Sandbox Code Playgroud)

fab*_*ian 5

使用 的方法Bindings或属性本身的更复杂的绑定很容易变得难以阅读和难以维护。

在这种情况下,我建议DoubleBinding使用自定义评估方法创建一个:

scoreProperty.bind(Bindings.createDoubleBinding(() -> {
    int size = results.size();
    return size == 0 ? 0d : ((double) successCountProperty.get()) / size;
}, results.sizeProperty(), successCountProperty));
Run Code Online (Sandbox Code Playgroud)