Swag Swagger
Swag Swagger

Reputation: 21

How to Exit primaryStage while opening a new stage in javafx

I am trying to figure out how to exit the primaryStage in javafx while opening another stage upon clicking a button, what is the code to remove the primary stage?

Upvotes: 1

Views: 11058

Answers (3)

Pande
Pande

Reputation: 21

set fx:id on your button

<JFXButton fx:id="btn_login" prefHeight="41.0" prefWidth="242.0" style="-fx-background-color: #0098DA;" text="Login" textFill="WHITE" GridPane.columnIndex="1" GridPane.rowIndex="4">

in your java controller

Stage stage = (Stage) btn_login.getScene().getWindow();

Actionevent

private void act_login(ActionEvent event) { //login pressed
    stage.close();
    Stage primaryStage = new Stage();
    Parent root = null;
    try {
        root = FXMLLoader.load(getClass().getResource("../fxmlFile/main.fxml"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    primaryStage.setTitle("Main Aplikasi Keuangan");
    primaryStage.setScene(new Scene(root, 600, 400));
    primaryStage.show();
}

Upvotes: 0

James_D
James_D

Reputation: 209340

You can use either

primaryStage.close();

or

primaryStage.hide();

According to the documentation, these are completely equivalent. It could be argued that since hide() is defined in the superclass, it is more general and therefore slightly preferred. For example, if you don't have a reference to the primaryStage directly, but to some node that is displayed in it, you can do

someNode.getScene().getWindow().hide();

but using close() this way requires a cast.

One "gotcha": by default, when the last window displayed is closed, the application will exit. So if you do

primaryStage.close();
Stage newStage = new Stage();
Scene newScene = new Scene(...);
newStage.setScene(newScene);
newStage.show();

bad things could happen, because you could implicitly exit the application before the new stage is shown(!). You can change the default behavior here with

Platform.setImplicitExit(false);

or, of course re-order the code so that the new stage is opened before the existing one is closed.

Upvotes: 1

L. Carbonne
L. Carbonne

Reputation: 481

The code to remove a stage is :

stage.close();

with variable stage corresponding to the stage you want to exit

Upvotes: 0

Related Questions