我在和Bindings.when斗争..。我试图创建一个百分比分数,当成功测试的数量发生变化(在下面的代码中反映为“successCountProperty”)或测试更改的总数(反映在“结果”的sizeProperty中)时更新。当我执行这段代码时,我得到java.lang.ArithmeticException: /为零。当我最初遇到异常时,我发现了Bindings.when().then().otherwise(),在我的头脑中应该可以解决这个问题。不幸的是,在执行这段代码时,尽管返回false的时间是'when‘,’然后‘仍在执行。有人能帮忙吗?
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));
}发布于 2018-03-12 15:11:54
使用Bindings方法或属性本身的更复杂的绑定很容易让人感到困惑、难以阅读和难以维护。
在这种情况下,我建议使用自定义评估方法创建DoubleBinding:
scoreProperty.bind(Bindings.createDoubleBinding(() -> {
int size = results.size();
return size == 0 ? 0d : ((double) successCountProperty.get()) / size;
}, results.sizeProperty(), successCountProperty));发布于 2018-03-12 15:25:40
你的问题是
Bindings.divide(successCountProperty, results.sizeProperty())立即进行评估,并且您似乎期望得到懒惰评价。
您可以编写自己的延迟除法器,它只在实际查询值时执行除法:
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();
}
}然后像这样使用:
scoreProperty.bind(
Bindings
.when(results.sizeProperty().greaterThan(0))
.then(
new LazyDivision(successCountProperty, results.sizeProperty())
)
.otherwise(0)
);https://stackoverflow.com/questions/49238141
复制相似问题