How can I obtain the primary Stage in a JavaFX application?


Question

Is it possible to get a reference to the primary Stage in a running JavaFX application ?.

The context of this question is that I would like to write a library that manipulates a JavaFX interface from another language (Prolog). In order to do this, my library requires access to the primary Stage. The objective is that the programmer of the JavaFX application does not have to explicit store a reference to the Stage object in the start method, so it should be transparent for the user interface designer (this is a related question in case more details are needed).

Part of this problem is getting a reference to the primary Stage object of the original JavaFX application ,so I was wondering if something like a static method somewhere could give me access to that.

1
8
5/23/2017 11:46:25 AM

Not sure of the right decision, but it works for my case.

Create static field in main class with getter and setter:

public class MyApp extends Application {

    private static Stage pStage;

    @Override
    public void start(Stage primaryStage) {
        setPrimaryStage(primaryStage);

        pStage = primaryStage;
        ...
    }

    public static Stage getPrimaryStage() {
        return pStage;
    }

    private void setPrimaryStage(Stage pStage) {
        MyApp.pStage = pStage;
    }
}

Next, in the necessary place calling getter. For example:

stageSecond.initOwner(MyApp.getPrimaryStage());
8
6/14/2018 4:56:54 AM

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