JavaFX - 带构造函数的对象

JavaFX - Object with Constructor

我正在使用 JavaFX,我的想法是拥有我自己的 JavaFX 对象,我可以像这样创建它:

public class Main {
    public static void main(String[] args) throws Exception 
        TSS t = new TSS();       
    }  
}

我的 JavaFX Main class 看起来像这样:

public class TSS extends Application {

    private Scene scene;
    private Stage stage;

    public void redrawGui() throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("tss.fxml"));
        scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }

    @Override
    public void start(Stage stage) throws Exception {
        this.stage = stage;
        this.stage = new Stage();
        Parent root = FXMLLoader.load(getClass().getResource("tss.fxml"));
        scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }
    public static void main(String[] args) {
        launch(args);
    } 
}

通常会调用 TSS 中的主要方法并正常工作,但我想在其构造函数中创建我自己的 TSS 对象,它会创建 Gui。

有人知道怎么做吗?

在 JavaFX 中,您应该(通常)将 Application subclass 视为 "main" class(即应用程序入口点) 及其 start(...) 方法替代 "traditional" Java 应用程序中的 main(...) 方法。

如果您想将代码分解为与 Application 子 class 分开的 class(这通常是个好主意),那么您可以这样做,但你需要稍微重新组织一下:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        TSS t = new TSS();
        Scene scene = new Scene(t.getView());
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    // not really needed in Java 8, but some IDEs need this to execute this class:
    public static void main(String[] args) { launch(args);}
}

然后你可以定义你自己的class如下:

public class TSS {

    private Parent view ;
    private TssController controller ; // controller class specified in FXML

    public TSS() throws Exception {
        load();
    }

    private void load() throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("tss.fxml"));
        view = loader.load();
        controller = loader.getController();
    }

    public Parent getView() {
        return view ;
    }

    public void restartGui() throws Exception {
        Scene scene = view.getScene();
        Stage stage = null ;
        if (scene != null) {
            Window window = scene.getWindow();
            if (window instanceof Stage) {
                stage = (Stage) window ;
            }
        }

        load();
        if (stage != null) {
            stage.setScene(new Scene(view));
        }
    }

    public void doOtherStuff() {
        controller.doSomething();
    }
}

您还可以考虑使用 FXML 文档中描述的 custom control 模式实现上面的 TSS class。我稍微喜欢我在这里展示的风格,因为它更喜欢组合而不是继承,但这是一个最小的区别。