Search code examples
javaeventsjavafxstage

How to close current stage when clicking a button to display new stage without making the components of the new stage inactive


Let's say I have a Stage A which contain two Buttons, oui Button opens a new Stage B, non closes A. what I'm trying to do is close A after clicking on oui Button and open B. I'm using showAndWait() to open B, then I try to execute A.close() which obviously fails being preceded by showAndWait(), when I tried to run A.close() before showAndWait() A closes, but then all Bcontrols including Buttons and Text Fields become inactive, is there any workaround ?

Here is the executed code when clicking on oui in order to open B Stage :

public class AController implements Initializable {

    @FXML
    private Button oui;
    @FXML
    private Button non;

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO

    }

    @FXML
    private void ouiBtnClick(ActionEvent event) throws IOException {

    FXMLLoader loader = new FXMLLoader();
    loader.setLocation(getClass().getResource("B.fxml"));

    Stage stage = new Stage();
    VBox mainPane = (VBox) loader.load();
        Scene scene = new Scene(mainPane);

    stage.setScene(scene);
    stage.initStyle(StageStyle.DECORATED);
    stage.setResizable(false);


        stage.showAndWait();
        nonBtnClick(); // method that close `A`


    }

    @FXML
    private void nonBtnClick() {
        Stage s = (Stage) non.getScene().getWindow();
        s.close();
    }

}

Solution

  • Using show instead of showAndWait did the trick . Thanks to Sedrick Jefferson comment.