Search code examples
javauser-interfacejavafxfxml

close fxml window by code, javafx


I need to close the current fxml window by code in the controller

I know stage.close() or stage.hide() do this in fx

how to implement this in fxml? I tried

private void on_btnClose_clicked(ActionEvent actionEvent) {
        Parent root = FXMLLoader.load(getClass().getResource("currentWindow.fxml"));    
        Scene scene = new Scene(root);

        Stage stage = new Stage();            
        stage.setScene(scene);
        stage.show();
}

but it doesn't work!

All help will be greatly appreciated. Thanks!


Solution

    1. give your close button an fx:id, if you haven't yet: <Button fx:id="closeButton" onAction="#closeButtonAction">
    2. In your controller class:

      @FXML private javafx.scene.control.Button closeButton;
      
      @FXML
      private void closeButtonAction(){
          // get a handle to the stage
          Stage stage = (Stage) closeButton.getScene().getWindow();
          // do what you have to do
          stage.close();
      }