Search code examples
javafxmlscenebuilder

I don't know how to close the main window in javafxml


I don't know how to close the main window in java fxml.

This part of code is in the class Main:

public void start(Stage primaryStage) throws Exception{
    Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
    Parent root2 = FXMLLoader.load(getClass().getResource("2ndwin.fxml"));
    Scene scene  = new Scene(root);
    primaryStage.setTitle("Hello World");
    primaryStage.setScene(scene);
    primaryStage.show();

    Scene scene2 = new Scene(root2);
    secondaryStage.setScene(scene2);
}

public void show(){
    secondaryStage.show();
}

I've got this. In controller i did this:

Main m = new Main();
m.show();`

but I still don't know how I can close primaryStage.

Please help me or tell me how I can create a new window and close the old window. I think this what I want to do - it isn't correct but I came up with it myself.


Solution

  • I do it by using an object in the stage you want to close to get the window

        Window currentStage = OBJECTINSCENE.getScene().getWindow();
    

    (Replace 'OBJECTINSCENE' with the id of anything in your scene). This gives you a reference to the stage you have open. Then call

    currentStage.hide();
    

    To close the stage when you want to.

    So your show function would be as follows

    public void show(){
        Window currentStage = OBJECTINSCENE.getScene().getWindow();
        secondaryStage.show();
        currentStage.hide();
    }