Search code examples
javajavafx-8keyevent

JavaFX 8 - How to get Backspace key pressed on HTMLEditor?


I want to mark a dialog as dirty when any key on the keyboard is pressed. Therefore I have this code:

editor.setOnKeyPressed(event -> dirtyProperty.set(true));

editor is a HTMLEditor control. It works for every KeyEvent (CTRL, etc. are also catched with this), but not for the Backspace and Delete key events. What I'm doing wrong here?


Solution

  • The line

    editor.setOnKeyPressed(event -> dirtyProperty.set(true));
    

    is shorthand of and thus equivalent to

    editor.addEventHandler(KeyEvent.KEY_PRESSED, event -> dirtyProperty.set(true));
    

    HTMLEditor seems to be consuming Backspace and Delete key events, before these events reach to the key handler defined like above.

    Instead of adding event handler, add a key filter to the editor

    editor.addEventFilter(KeyEvent.KEY_PRESSED, event -> dirtyProperty.set(true));
    

    Since event filters are invoked as soon as when the event is received, before any event handlers. Whereas event handlers are invoked when the event is in bubbling phase, namely when the event is going back to parent node.