I have a special case where I want to add a listener to a visible property, and then have the listener removed when the property is no longer visible. I only want the listener to fire one time and then be removed.
ie
ChangeListener<Boolean> listener= (obs, ov, nv) -> {
if(!nv){
//do my processing
node.visibleProperty().removeListener(listener); }
}
};
node.visibleProperty().addListener(listener);
However it tells me that the variable listener may not have been initialized. If I try by making it null, then creating it, it complains that it is not effectively final
Is this possible?
You can either make listener
an instance variable, instead of a local variable, or you can use an anonymous inner class (in which you can use the keyword this
to refer to itself):
ChangeListener<Boolean> listener = new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> obs, Boolean ov, Boolean nv) {
if (! nv) {
node.visibleProperty().removeListener(this);
}
}
};
node.visibleProperty().addListener(listener);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With