alfredo1389 alfredo1389 - 1 year ago 68
Java Question

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

but it doesn't work!

All help will be greatly appreciated. Thanks!

Answer Source
  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;
    private void closeButtonAction(){
        // get a handle to the stage
        Stage stage = (Stage) closeButton.getScene().getWindow();
        // do what you have to do