子类化JavaFX应用程序 [英] Subclassing a JavaFX Application

查看:53
本文介绍了子类化JavaFX应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题是我发布的问也会收到该错误.我要实现的是,当按下Enter键时,在SubClass中调用方法exec(String command).这是我当前的SuperClass代码:

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

推荐答案

代替创建新的SubClass实例,请尝试调用静态方法SubClass.launch(args) JavaFX会自行创建新的SubClass实例.

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

这篇关于子类化JavaFX应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆