简体   繁体   中英

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM