How to pass parameters to JavaFX application?


Question

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 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.

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

1
12
7/7/2014 1:31:10 PM

Accepted Answer

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!

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);
    }
}
4
7/10/2014 9:29:51 AM

Starting with JavaFX 9 you can trigger the launch of the JavaFX platform "manually" using the public API. The only drawback is that the stop method is not invoked the way it would be in application started via Application.launch:

public class MainEntry {
    public static void main(String[] args) {
        Controller controller = new Controller();

        final MainStage mainStage = new MainStage(controller);
        mainStage.init();

        Platform.startup(() -> {
            // create primary stage
            Stage stage = new Stage();

            mainStage.start(stage);
        });
    }
}

The Runnable passed to Platform.startup is invoked on the JavaFX application thread.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon