12

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.

Community
  • 1
  • 1
Sergio
  • 8,532
  • 11
  • 52
  • 94
  • See this too:[JavaFX: How to get stage from controller during initialization](https://stackoverflow.com/questions/13246211/javafx-how-to-get-stage-from-controller-during-initialization) – knollmaj Jun 10 '19 at 10:20

4 Answers4

14

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());
MGT
  • 173
  • 12
DaddyRatel
  • 729
  • 3
  • 13
  • 30
4

I was just researching this issue. There does not seem to be any built-in method to get the primary stage. You can use node.getScene().getWindow() from a node within the main window but not within other windows. Explicitly storing the primaryStage reference is apparently the only reliable way to do this.

2

Since you receive the primary stage in the Application#start(Stage primaryStage) method you could keep it around.

Nicolas Mommaerts
  • 3,207
  • 4
  • 35
  • 55
0

Just to complement the VladmirZ Answer. Follow the first part. Then. For hide or close the primaryStage on Action Button.

I do this. Example

void ActionButton(ActionEvent event) throws Exception {


    Stage StageTest = TabelaApp.getTabelaStage(); // call the getter. In my case TabelaApp.getTabelaStage
    StageTest.hide(); //Or Close

    // This Call the Stage you want
    Parent root = FXMLLoader.load(getClass().getResource("/tabela2/FrmTabela2.fxml"));
    Scene scene = new Scene(root);
    Stage stage = new Stage();
    stage.setScene(scene);
    stage.show();


}
  • Try to make your answer a bit more constructive and explain why it works. Also, try to make the answer more clear and not just an example. – makertech81 Apr 24 '20 at 16:32