首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaFX 8 Bindings.when和Bindings.divide创建除以零

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

Stack Overflow用户
提问于 2018-03-12 14:50:36
回答 2查看 731关注 0票数 3

我在和Bindings.when斗争..。我试图创建一个百分比分数,当成功测试的数量发生变化(在下面的代码中反映为“successCountProperty”)或测试更改的总数(反映在“结果”的sizeProperty中)时更新。当我执行这段代码时,我得到java.lang.ArithmeticException: /为零。当我最初遇到异常时,我发现了Bindings.when().then().otherwise(),在我的头脑中应该可以解决这个问题。不幸的是,在执行这段代码时,尽管返回false的时间是'when‘,’然后‘仍在执行。有人能帮忙吗?

代码语言:javascript
复制
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));
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-03-12 15:11:54

使用Bindings方法或属性本身的更复杂的绑定很容易让人感到困惑、难以阅读和难以维护。

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

代码语言:javascript
复制
scoreProperty.bind(Bindings.createDoubleBinding(() -> {
    int size = results.size();
    return size == 0 ? 0d : ((double) successCountProperty.get()) / size;
}, results.sizeProperty(), successCountProperty));
票数 5
EN

Stack Overflow用户

发布于 2018-03-12 15:25:40

你的问题是

代码语言:javascript
复制
Bindings.divide(successCountProperty, results.sizeProperty())

立即进行评估,并且您似乎期望得到懒惰评价

您可以编写自己的延迟除法器,它只在实际查询值时执行除法:

代码语言:javascript
复制
class LazyDivision extends DoubleBinding
{
    private IntegerProperty dividend;
    private ReadOnlyIntegerProperty divisor;

    LazyDivision(final IntegerProperty dividend, final ReadOnlyIntegerProperty divisor)
    {
        this.dividend = dividend;
        this.divisor = divisor;
    }

    @Override
    protected double computeValue()
    {
        return dividend.getValue() / divisor.getValue().doubleValue();
    }
}

然后像这样使用:

代码语言:javascript
复制
scoreProperty.bind(
    Bindings
        .when(results.sizeProperty().greaterThan(0))
        .then(
            new LazyDivision(successCountProperty, results.sizeProperty())
        )
        .otherwise(0)
);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49238141

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档