0

I wrote the defaultCloseOperation function of the primaryStage, but I have an exit button too and I want to run that defaultCloseOperation. I tried to call the close() and the hide() methods of the stage but it exit immediately without calling my defaultCloseOperation function, but I need to call it because I need to release all the resources from the server side when I close the client.

GeelZyen
  • 11
  • 4

2 Answers2

4

Do not do this on a closing operation of a Stage.

This is what the Application.stop method should be used for.

@Override
public void stop() throws Exception {
    // TODO: release resources here
}

If there are resources used for one of multiple windows however, you should use an event handler for the onHidden event - no need to extend Stage:

stage.setOnHidden(event -> {
    // TODO: release resources here
});
fabian
  • 80,457
  • 12
  • 86
  • 114
1

you can see it:

stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    @Override public void handle(WindowEvent t) {
        System.out.println("CLOSING");
    }
});

and here:

new EventHandler<ActionEvent>() {
  @Override public void handle(ActionEvent actionEvent) {
    // take some action
    ...
    // close the dialog.
    Node  source = (Node)  actionEvent.getSource(); 
    Stage stage  = (Stage) source.getScene().getWindow();
    stage.close();
  }
}

more of explanation you can read here

Vasyl Lyashkevych
  • 1,920
  • 2
  • 23
  • 38
  • 1
    Can you explain a bit more what this is supposed to do? Calling `stage.close()` will **not** invoke the `onCloseRequest()` handler. It's not clear if that's what you intend. If you want an event handler that is invoked no matter how the window is closed, you should use `stage.setOnHidden()`. – James_D May 26 '17 at 16:54