Search code examples
javajavafxjavafx-2

JavaFx close window on pressing esc not working on table view?


I've used the following function to close the Stage when pressing escape key. It works fine but it doesn't work when my table has the keyboard focus.

scene.setOnKeyPressed(new EventHandler<KeyEvent>() 
{
  @Override
  public void handle(KeyEvent evt) 
  {
     if(evt.getCode().equals(KeyCode.ESCAPE))
     {
        dialogStage.close();
     }
  }
});

Solution

  • It seems the KeyEvent event is being consumed by the child node TableView. So the right approach will be attaching EventFilter instead of EventHandler:

    scene.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent evt) {
            if (evt.getCode().equals(KeyCode.ESCAPE)) {
                stage.close();
            }
        }
    });
    

    To see the difference between event handlers and filters refer to Handling JavaFX Events.