Adding input filter to TextField blocks default handling of ESC key

David :

Context: JDK 8 & JavaFX

I have a TextField control that is used in a dialog. It is the first edit control, so it gets the focus when the dialog opens. The dialog has a button configured as the cancel button (Button.setCancelButton(true))

With a plain TextField, if I hit ESC immediately after the dialog opens, the dialog is closed (as expected).

However, once I add a TextFormatter with input filter to the TextField, the ESC keypress appears to be being consumed by the input control and ESC no longer closes the dialog.

The TextFormatter only has an input filter (to restrict the input control to just digits), but the input filter does not get invoked on the ESC keypress - because the content of the field has not changed.

It's a fairly minor issue, but it's annoying not having consistent behaviour, and not being able to just hit ESC to dismiss the dialog. Any ideas on how to ensure that the ESC keypress is propagated/not consumed, so that it is handled by the dialog?

Edit:

My question appears to be a duplicate of this one: Escape from a Number TextField in a JavaFX dialog. Which of course I failed to find despite trawling through Google before posting... TLDR; the TextFormatter class fails to forward the ESC keypress event on.

VGR :

I think the easiest approach is to avoid trying to “fix” the TextField and TextFormatter, and just add a key listener:

textField.setOnKeyPressed(e -> {
    if (e.getCode() == KeyCode.ESCAPE) {
        dialog.setResult(ButtonType.CANCEL);
    }
});

If the Dialog is not an Alert (or more precisely, is not a Dialog<ButtonType>), you can locate the button and activate it yourself:

textField.setOnKeyPressed(e -> {
    if (e.getCode() == KeyCode.ESCAPE) {
        Button cancelButton = (Button)
            dialog.getDialogPane().lookupButton(ButtonType.CANCEL);
        cancelButton.fire();
    }
});

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=147278&siteId=1