Subclassing a JavaFX Application

你。 提交于 2019-12-12 06:09:22

问题


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);
}

回答1:


Instead of creating new instance of SubClass, try to call static method SubClass.launch(args) JavaFX will create new SubClass instance by itself.



来源:https://stackoverflow.com/questions/28204292/subclassing-a-javafx-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!