JavaFX - 属性"无效"的含义

use*_*565 6 javafx listener bindable observable

在JavaFX的上下文中,在更改时属性"无效"是什么意思?我不明白使用这个术语的原因.

JavaFX属性是可观察的对象并包装字段值.因此,当属性更新或变为无效时,会通知其listerners /观察者.这是什么意思?

Asi*_*taq 7

我在这里找到了很好的解释

在此输入图像描述

调用intProperty.set(7168)时,它会向otherProperty触发invalidation事件.收到此无效事件后,otherProperty只会记下其值不再有效的事实.它不会通过查询intProperty的值来立即重新计算其值.稍后在调用otherProperty.get()时执行重新计算.想象一下,如果不是像上面的代码那样只调用一次intProperty.set(),我们多次调用intProperty.set(); otherProperty仍然只重新计算一次其值.

经过测试,我发现了这个例子.

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;

public class InvalidMean{
    public static void main(String[] args){
        IntegerProperty num1 = new SimpleIntegerProperty(15);
        IntegerProperty num2 = new SimpleIntegerProperty(10);
        // num2.bind(num1);
        // num1.set(56);
        System.out.println(num2);
    }
}
Run Code Online (Sandbox Code Playgroud)

运行此代码您将获得此输出:

IntegerProperty [value: 10]
Run Code Online (Sandbox Code Playgroud)

现在从注释行中删除注释.你会得到这个输出.

IntegerProperty [bound, invalid]
Run Code Online (Sandbox Code Playgroud)

num2由于新值已到达但尚未更新,因此该值变为无效.正如JavaFX Doc所描述的那样,只是因为懒惰的评估.

JavaFX绑定和属性实现都支持延迟评估,这意味着当发生更改时,不会立即重新计算该值.如果随后请求值,则重新计算稍后发生.

如果您希望该值应该是有效的调用num2.getValue();num2.get();之前System.out.println(num2);您将看到属性将是有效的.

注意:在上面的示例中num2.bind(num1);,num1.set(56);两者都会使值无效,num2因为bind已经更改了值num2并且set()还尝试更改该值.


Spo*_*ted 0

这都是关于惰性评估的。Devoxx 2011 会议的这段视频帮助我理解了这个概念。

对您来说有趣的事情从 ~5:00 开始。