Sergio
Sergio

Reputation: 8672

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

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.

Upvotes: 13

Views: 25855

Answers (4)

Thiago Sarkis
Thiago Sarkis

Reputation: 19

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


}

Upvotes: 0

DaddyRatel
DaddyRatel

Reputation: 739

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

Upvotes: 15

user574171
user574171

Reputation:

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.

Upvotes: 4

Nicolas Mommaerts
Nicolas Mommaerts

Reputation: 3263

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

Upvotes: 2

Related Questions