gpt4 book ai didi

JavaFX InvalidationListener 或 ChangeListener

转载 作者:行者123 更新时间:2023-12-02 17:59:55 38 4
gpt4 key购买 nike

我只关心属性是否已更改,而不是新值。

注册 InvalidationListener 而不是 ChangeListener 是否有利?

我假设对属性的更改首先会使该属性无效并通知所有无效监听器。仅当注册了更改监听器或有人请求此属性时,该属性才会“验证”/重新计算,并且所有更改监听器都会使用新值进行更新。

由于我对实际值不感兴趣,因此我认为仅监听失效事件(属性已更改但未重新计算,某种中间状态)具有性能优势。

最佳答案

您需要为此实现一个 ChangeListenerInvalidationListener 仅在值变得无效时执行。请参阅docs .

来自ObservableValue的java文档:

An ObservableValue generates two types of events: change events and invalidation events. A change event indicates that the value has changed. An invalidation event is generated, if the current value is not valid anymore. This distinction becomes important, if the ObservableValue supports lazy evaluation, because for a lazily evaluated value one does not know if an invalid value really has changed until it is recomputed. For this reason, generating change events requires eager evaluation while invalidation events can be generated for eager and lazy implementations.

我添加了一个简单的示例

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的问题是,如果值再次无效,您将不会收到更改通知,因为它已经无效。您必须为此使用更改监听器。

在属性上注册更改监听器将禁用延迟计算,因此每次更改监听器被触发时都会触发失效事件。

在我添加的示例中尝试一下。

关于JavaFX InvalidationListener 或 ChangeListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45117076/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com