Search code examples
javafxcontrollerwebcamfxml

JavaFX FXML Controller onClose or equivalent?


Is there a method for a JavaFX controller that gets called when the user leaves that view in the application? The opposite of the initialize() method basically.

I want to do this because I have a page that shows a webcam stream waiting for the user to press a button that takes a snapshot, and I need to close that stream if the user doesn't take a snapshot and leaves the screen. Any other ways of doing this would be appreciated too.

Thanks!


Solution

  • You can use the window's hiding event...

    private void detachHook(final Node parent) {
        parent.getScene().getWindow()
            .addEventFilter(WindowEvent.WINDOW_HIDING, event -> {
              //Kill your webcam stream
        });
    }
    

    You will have to check if you also get the parent as we do in our application, but the window hiding event should work if a node and a scene are present.