Search code examples
javainheritancejavafxextendssuper

JavaFX use superclass in EventHandler


I have multiple controller-classes, which extend another controller. When I create an EventHandler in an extending controller-class, I can't use "super.something". It works in a normal method, but not in an EventHandler. Is there any other option?

Here is a little example excerpt:

public class ViewController {

    @FXML
    private TextField idField;

    public TextField getIdField() {
        return idField;
    }
}   

-

public class ExtendingViewController extends ViewController {

    @FXML
    private Label testLabel;

    private EventHandler<ActionEvent> createBtnHandler = new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {

               //This does not work. "super" does not seem to exist in this method.
               testLabel.setText(super.getIdField());

            }
        };
    }

    public void testMethod(){
        //this does work
        testLabel.setText(super.getIdField());
    }
}

Solution

  • There's no need to use super here. If you leave out the super., the java compiler checks the anonymus class for a getIdField method and since it does not find one, it checks the containing class for this method. (Using super or this in testMethod does not change the result, since getIdField is not overwritten in ExtendingViewController.)

    testLabel.setText(getIdField().getText());
    

    You can however access members of the superclass of the containing class using ContainingClass.super:

    private EventHandler<ActionEvent> createBtnHandler = new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            testLabel.setText(ExtendingViewController.super.getIdField().getText());
        }
    };