问题描述
我只对属性是否已更改感兴趣,而对新值不感兴趣.
I am only interested whether a property has changed or not, but not in the new value.
注册InvalidationListener
而不是ChangeListener
是否有利?
我假设对属性的更改会首先使该属性无效并通知所有无效侦听器.仅当注册了变更侦听器或有人请求此属性时,该属性才会被验证"/重新计算,并且所有变更侦听器都将使用新值进行更新.
I was assuming that a change to a property does first invalidate the property and notifies all invalidation listeners. Only if there are change listeners registered, or somebody requests this property, the property is 'validated'/ re-computed and all change listeners are updated with the new value.
由于我对实际值不感兴趣,因此我认为仅侦听无效事件(属性已更改但未重新计算,是某种中间状态)具有性能优势.
Since I am not interested in the actual value, I assume it is a performance advantage to listen only for invalidation events (property has changed but was not re-calculated, some kind of intermediate state).
推荐答案
您需要为此实现ChangeListener
.仅当值变为无效时才执行InvalidationListener
.请参见文档.
You need to implement a ChangeListener
for that. A InvalidationListener
is only executed once the value becomes invalid. See the docs.
我添加了一个简单的示例
I have added a simple example
public static void main(String[] args) {
SimpleIntegerProperty one = new SimpleIntegerProperty(1);
SimpleIntegerProperty two = new SimpleIntegerProperty(0);
// the binding we are interested in
NumberBinding sum = one.add(two);
sum.addListener(observable -> System.out.println("invalidated"));
// if you add a value change listener, the value will NOT be evaluated lazy anymore
//sum.addListener((observable, oldValue, newValue) -> System.out.println("value changed from " + oldValue + " to " + newValue));
// is valid, since nothing changed so far
System.out.println("sum valid: " + sum.isValid());
// will invalidate the sum binding
two.set(1);
one.set(2); // invalidation event NOT fired here!
System.out.println("sum valid: " + sum.isValid());
// will validate the sum binding, since it is calculated lazy when getting the value
System.out.println("sum: " + sum.getValue());
System.out.println("sum valid: " + sum.isValid());
}
使用InvalidationListener
的问题是如果该值再次变为无效,则不会通知您更改,因为该值已经无效.您必须为此使用更改侦听器.
The problem in using the InvalidationListener
is that you will not be notified for changes if the value becomes invalid again, since it is already invalid. You have to use a change listener for that.
在属性上注册更改侦听器将禁用延迟评估,因此,每次触发更改侦听器时都会触发无效事件.
Registering a change listener on the property will disable lazy evaluation, so the invalidation event gets fired every time the change listener gets fired.
在我添加的示例中尝试一下.
Try it out in the sample i added.
这篇关于JavaFX InvalidationListener或ChangeListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!