Dhiren Hamal
Dhiren Hamal

Reputation: 1012

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

Upvotes: 5

Views: 2616

Answers (2)

Dmytro Maslenko
Dmytro Maslenko

Reputation: 2297

I had the same problem but found the target of KeyEvent is the TableView, not parent stage, that is why the parent doesn't get Esc event.

My variant based on EventHandler (bubbling phase):

myTable.setOnKeyReleased(event -> {
    if (event.getCode() == KeyCode.ESCAPE) {
        stage.close();
    }
});

Upvotes: 0

Uluk Biy
Uluk Biy

Reputation: 49215

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.

Upvotes: 5

Related Questions