Return to Main Menu when pressing ESC with JavaFx

Question:

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

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

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
    }
});
Scroll to Top