I am running my JavaFX application like this:
public class MainEntry {
public static void main(String[] args) {
Controller controller = new Contr
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.
I don't even have an instance of my MainStage class !
Your main method doesn't need an instance of MainStage
to call the start() of your MainStage
. This job is done automatically by the JavaFX launcher.
From Docs
The entry point for JavaFX applications is the Application class. The JavaFX runtime does the following, in order, whenever an application is launched:
Constructs an instance of the specified Application class
- Calls the init() method
- Calls the start(javafx.stage.Stage) method
- Waits for the application to finish, which happens when either of the following occur: the application calls Platform.exit() the last window has been closed and the implicitExit attribute on Platform is true
- Calls the stop() method
and
The Java launcher loads and initializes the specified Application class on the JavaFX Application Thread. If there is no main method in the Application class, or if the main method calls Application.launch(), then an instance of the Application is then constructed on the JavaFX Application Thread.
How to pass non-String parameter (controller in my case) to MainStage instance?
Why do you need to pass non-String parameter to MainStage
? If you need an controller object, just fetch it from the FXML
Example
public class MainEntry extends Application {
@Override
public void start(Stage stage) throws Exception {
FXMLLoader loader = new FXMLLoader();
Pane pane = (Pane) loader.load(getClass().getResourceAsStream("sample.fxml"));
//Get the controller
Controller controller = (Controller)loader.getController();
Scene scene = new Scene(pane, 200, 200);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);// or launch(MainEntry.class)
}
}