【问题标题】:Subclassing a JavaFX Application子类化 JavaFX 应用程序
【发布时间】:2015-03-28 01:31:37
【问题描述】:

这个问题是对我发布的问题 How do you call a subclass method from a superclass in Java? 的后续问题。好吧,我得到了答案,但是我的 SuperClass 是 extends Application 的 JavaFX 应用程序,每当我尝试使用抽象类作为我的应用程序类时,我都会收到以下错误:构造函数中的 java.lang.reflect.InvocationTargetException。即使应用程序类不是抽象的,如果我尝试调用new SubClass().create("title");,我也会收到该错误。我想要实现的是在按下回车键时调用子类中的方法exec(String command)。这是我当前的超类代码:

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

【问题讨论】:

  • 任何有兴趣回答这个问题的人都可能会找到source code for the JavaFX launcher interesting - 特别是(无需花费更多时间来分析用例)我不确定是否启动作为应用程序子类的子类的应用程序是受支持的功能。

标签: java inheritance javafx-8


【解决方案1】:

不要创建新的子类实例,而是尝试调用静态方法SubClass.launch(args)JavaFX 将自己创建新的子类实例。

【讨论】:

  • ERRRMERRRGRRRRDDDD 非常感谢。你真的解决了我所有的问题。
  • 我知道这个问题已经过时了,但是否可以像您最初所说的那样在超类中而不是在子类中保留对 launch() 的调用?
猜你喜欢
  • 2013-03-31
  • 1970-01-01
  • 2017-01-11
  • 1970-01-01
  • 2020-03-13
  • 1970-01-01
  • 2018-05-17
  • 1970-01-01
  • 2019-06-01
相关资源
最近更新 更多