如何将参数传递给

如何将参数传递给

本文介绍了如何将参数传递给 JavaFX 应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在像这样运行我的 JavaFX 应用程序:

I am running my JavaFX application like this:

public class MainEntry {
    public static void main(String[] args) {
        Controller controller = new Controller();
        Application.launch(MainStage.class);
    }
}

MainStage 类扩展了 Appication.Application.launch 在一个特殊的 FX 线程中启动我的 JavaFX 窗口,但在我的主方法中,我什至没有我的 MainStage 类的实例.

MainStage class extends Appication. Application.launch starts my JavaFX window in a special FX-thread, but in my main method I don't even have an instance of my MainStage class.

如何将非字符串参数(在我的例子中为 controller)传递给 MainStage 实例?这是一个有缺陷的设计吗?

How to pass non-String parameter (controller in my case) to MainStage instance? Is it a flawed design?

推荐答案

通常,除了传递给主应用程序的程序参数之外,不需要将参数传递给主应用程序.人们想要这样做的唯一原因是创建一个可重用的Application.但是 Application 不需要可重用,因为它是组装应用程序的一段代码.将 start 方法视为新的 main

Usually, there is no need to pass arguments to the main application other than the program arguments passed to your main. The only reason why one wants to do this is to create a reusable Application. But the Application does not need to be reusable, because it is the piece of code that assembles your application. Think of the start method to be the new main!

因此,与其编写在 main 方法中配置的可重用 Application,应用程序本身应该是配置器并使用可重用组件在start 方法,例如:

So instead of writing a reusable Application that gets configured in the main method, the application itself should be the configurator and use reusable components to build up the app in the start method, e.g.:

public class MyApplication extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        // Just on example how it could be done...
        Controller controller = new Controller();
        MyMainComponent mainComponent = new MyMainComponent(controller);
        mainComponent.showIn(stage);
    }

    public static void main(String[] args) {
        Application.launch(args);
    }
}

这篇关于如何将参数传递给 JavaFX 应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:42