gpt4 book ai didi

java - 如何在 JavaFX 的 ChangeListener 中获取对 Property ChangeListener 的引用?

转载 作者:行者123 更新时间:2023-11-29 04:26:49 25 4
gpt4 key购买 nike

我想添加到属性监听器,等待此监听器被调用并删除此监听器。所以我写了下面的代码:

    ChangeListener<String> listener = (observable, oldValue, newValue) -> {
textField.setStyle("-fx-border-color:black");
textField.textProperty().removeListener(listener); //LINE X
};
textField.textProperty().addListener(listener);

但是,在 LINE X 中,我得到 Variable listener might not have been initialized。如何在 ChangeListener 中获取对属性 ChangeListener 的引用以将其删除?

最佳答案

来自 JLS,section 15.27.2 :

Unlike code appearing in anonymous class declarations, the meaning of names and the this and super keywords appearing in a lambda body, along with the accessibility of referenced declarations, are the same as in the surrounding context (except that lambda parameters introduce new names).

...

Practically speaking, it is unusual for a lambda expression to need to talk about itself (either to call itself recursively or to invoke its other methods), while it is more common to want to use names to refer to things in the enclosing class that would otherwise be shadowed (this, toString()). If it is necessary for a lambda expression to refer to itself (as if via this), a method reference or an anonymous inner class should be used instead.

(我的重点。)

因此,简而言之,lambda 表达式无法引用自身。您需要将其重构为匿名内部类:

ChangeListener<String> listener = new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
textField.setStyle("-fx-border-color:black");
textField.textProperty().removeListener(this);
}
};
textField.textProperty().addListener(listener);

当然,此时您可能不再需要引用:

textField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
textField.setStyle("-fx-border-color:black");
textField.textProperty().removeListener(this);
}
});

关于java - 如何在 JavaFX 的 ChangeListener 中获取对 Property ChangeListener 的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45867545/

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