简体   繁体   English

为什么我不能从事件侦听器调用方法,而不能在类中的其他地方调用方法?

[英]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: 我在JavaFX GUI的控制器类中具有以下代码,该类为组合框提供了事件侦听器:

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? 更具体地说,我可以在该侦听器也驻留的控制器中的initialize()函数内调用它。为什么会有这个问题?

Because this within the listener refers to the listener current instance, not to the controller instance. 因为this听者内指的是监听当前实例,而不是控制器实例。 To refer to the container instance, use the syntax ControllerClassName.this . 要引用容器实例,请使用语法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. 在此匿名类ChangeListener ,没有名为setClassList()方法,因此编译器对此有所抱怨。 You could try simply avoid using this keyword: 您可以尝试避免使用this关键字:

setClassList(courseProcessed);

OR 要么

You could also try this: 您也可以尝试以下方法:

YourClass.this.setClassList(courseProcessed);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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