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