Return to the Start Menu when pressing ESC with JavaFx

Posted on

Question :

How can I get my application back to the start menu after pressing ESC . Currently I can use KeyEvent only when some component is associated, such as TextField , Button , etc. I just want to press Esc without any component being selected and the application returns to the main menu. Example of how I do (Associating a component):

txtPesquisar.setOnKeyPressed(k -> {
            final KeyCombination ENTER = new KeyCodeCombination(KeyCode.ENTER);
            if (ENTER.match(k)) {


Answer :

Just add a handler to your scene.

scene.addEventHandler(KeyEvent.KEY_PRESSED, (KeyEvent t) -> {
    if (t.getCode() == KeyCode.ESCAPE) {
        //codigo para ir ao menu inicial


Leave a Reply

Your email address will not be published. Required fields are marked *