Search code examples
javajavafxstage

Close Stage with Escape button in JavaFx


I've created the following function in order to close any pop up Stage in my program:

public void escapeKeyPressed(final KeyEvent keyEvent , Stage diolog) {
        if (keyEvent.getCode() == KeyCode.ESCAPE) {
            diolog.close();
        }
    }

Then, I have a clickable image where can be clicked and a form will pop up :

The problem is when I call the function I get error for the first argument . Here is how I call it ;)

 escapeKeyPressed( KeyCode.ESCAPE ,dialog );

Does any body know how can I fix that ?


Solution

  • Your method signature is (final KeyEvent keyEvent, Stage diolog) and you pass a KeyCode as first argument which is not a KeyEvent.

    You can pass the original KeyEvent instead, to fulfil the signature as:

    yourPopUp.setOnKeyPressed((KeyEvent event) -> escapeKeyPressed(event, dialog ));
    

    But it would be much cleaner if you would update the method signature to accept the KeyCode directly:

    public void escapeKeyPressed(KeyCode keyCode , Stage diolog) {
        if (keyCode == KeyCode.ESCAPE)
            diolog.close();
    }
    

    In this case you can have the original call as:

    escapeKeyPressed(KeyCode.ESCAPE, dialog );