Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a listener when the listener executes

Tags:

javafx-8

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?

like image 305
purring pigeon Avatar asked Sep 11 '25 20:09

purring pigeon


1 Answers

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);
like image 140
James_D Avatar answered Sep 13 '25 14:09

James_D