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());
}
}
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());
}
};
This doesn't work because super is a relative reference. When referencing super from testMethod
super is the ViewController
, but when referencing super from createBtnHandler
super is the EventHandler
super class. (Event handler inherits from object so object would be the super) See - https://docs.oracle.com/javase/8/javafx/api/javafx/event/EventHandler.html
To make this work you could make a class that inherits EventHander
and pass a reference to the method you would like to invoke.
public class CustomEventHandler implements EventHandler<ActionEvent> {
private IEventsHandler mEventsHandler;
public CustomEventHandler(IEventsHandler eventsHandler)
{
mEventsHandler = eventsHandler;
}
@Override
public void handle(ActionEvent event) {
mEventsHandler.testMethod();
}
}
public interface IEventsHandler {
void testMethod();
}
public class ExtendingViewController extends ViewController implements IEventsHandler {
@FXML
private Label testLabel;
private EventHandler<ActionEvent> createBtnHandler = new CustomEventHandler(this);
public void testMethod(){
testLabel.setText(super.getIdField());
}
}
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.