简体   繁体   中英

Why can't I call method from event listener but can elsewhere in class?

I have the following code in a controller class in for a JavaFX GUI that provides an event listener for a combo box:

courseComboBox.getSelectionModel().selectedItemProperty()
                .addListener(new ChangeListener<String>() {
                    @Override
                    public void changed(
                            ObservableValue<? extends String> selected,
                            String oldValue, String newValue) {

                           // Do stuff

    }
});

However, when I try to call another method from within it I am unable to:

courseComboBox.getSelectionModel().selectedItemProperty()
                    .addListener(new ChangeListener<String>() {
                        @Override
                        public void changed(
                                ObservableValue<? extends String> selected,
                                String oldValue, String newValue) {

                                this.setClassList(courseProcessed);

                               // Do Stuff

   }
});

I can call the method elsewhere in the class, though. More specifically, I can call it inside the initialize() function in my controller that this listener also resides in. Why am I having this problem?

Because this within the listener refers to the listener current instance, not to the controller instance. To refer to the container instance, use the syntax ControllerClassName.this .

Problem here is:

new ChangeListener<String>() {
   @Override
   public void changed(ObservableValue<? extends String> selected, String oldValue, String newValue) {
       this.setClassList(courseProcessed);// `this` refers to the current instance of the anonymous class `ChangeListener`
   }
}

In this anonymous class ChangeListener there is no method named setClassList() so the compiler complaints about it. You could try simply avoid using this keyword:

setClassList(courseProcessed);

OR

You could also try this:

YourClass.this.setClassList(courseProcessed);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM