ferrerverck ferrerverck - 5 months ago 50
Java Question

How to pass parameters to JavaFX application?

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?

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