This question is a follow up to a question I posted asking How do you call a subclass method from a superclass in Java?. Well I got my answer but my SuperClass is a JavaFX application that extends Application and whenever I attempt to use an abstract class as my application class I get the following error: java.lang.reflect.InvocationTargetException in the constructor. Even if the application class is not abstract I get that error if I attempt to call new SubClass().create("title");. What I'm looking to achieve is call a method exec(String command) in the SubClass when the enter key is pressed. Here is my current SuperClass code:
public abstract class Console extends Application {
private String title;
private static Text output = new Text();
public void create(String title) {
this.title = title;
launch();
}
public void start(Stage stage) {
stage.setOnCloseRequest((WindowEvent event) -> {
System.exit(0);
});
stage.setTitle(title);
stage.setResizable(false);
Group root = new Group();
Scene scene = new Scene(root, 800, 400);
stage.setScene(scene);
ScrollPane scroll = new ScrollPane();
scroll.setContent(output);
scroll.setMaxWidth(800);
scroll.setMaxHeight(360);
TextField input = new TextField();
input.setLayoutX(0);
input.setLayoutY(380);
input.setPrefWidth(800);
scene.setOnKeyPressed((KeyEvent event) -> {
if(event.getCode() == KeyCode.ENTER) {
exec(input.getText());
input.clear();
}
});
root.getChildren().add(scroll);
root.getChildren().add(input);
stage.show();
}
public static void appendOutput(String value) {
Platform.runLater(() -> {
output.setText(output.getText() + "\n" + value);
});
}
protected abstract void exec(String command);
}
解决方案
Instead of creating new instance of SubClass, try to call static method SubClass.launch(args) JavaFX will create new SubClass instance by itself.