简体   繁体   English

将输入过滤器添加到TextField会阻止ESC键的默认处理

[英]Adding input filter to TextField blocks default handling of ESC key

Context: JDK 8 & JavaFX 上下文:JDK 8和JavaFX

I have a TextField control that is used in a dialog. 我有一个对话框中使用的TextField控件。 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)) 该对话框具有配置为取消按钮的按钮(Button.setCancelButton(true))

With a plain TextField, if I hit ESC immediately after the dialog opens, the dialog is closed (as expected). 使用纯文本字段时,如果在对话框打开后立即单击ESC,则对话框将关闭(按预期方式)。

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. 但是,一旦我将具有输入过滤器的TextFormatter添加到TextField,则ESC按键似乎已被输入控件占用,并且ESC不再关闭对话框。

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. TextFormatter仅具有一个输入过滤器(以将输入控件限制为仅数字),但是在ESC按键上不会调用该输入过滤器-因为该字段的内容没有更改。

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. 这是一个相当小的问题,但是令人讨厌的是没有一致的行为,并且无法直接按ESC来关闭对话框。 Any ideas on how to ensure that the ESC keypress is propagated/not consumed, so that it is handled by the dialog? 关于如何确保传播/不消耗ESC按键,以便由对话框进行处理的任何想法?

Edit: 编辑:

My question appears to be a duplicate of this one: Escape from a Number TextField in a JavaFX dialog . 我的问题似乎是该问题的重复: 从JavaFX对话框中的Number TextField转义 Which of course I failed to find despite trawling through Google before posting... TLDR; 尽管在发布前通过Google进行了拖网搜索,但我当然找不到哪个... TLDR; the TextFormatter class fails to forward the ESC keypress event on. TextFormatter类无法继续转发ESC按键事件。

I think the easiest approach is to avoid trying to “fix” the TextField and TextFormatter, and just add a key listener: 我认为最简单的方法是避免尝试“修复” TextField和TextFormatter,而只需添加一个关键侦听器:

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: 如果对话框不是警报(或更准确地说,不是Dialog<ButtonType> ),则可以找到该按钮并自己激活它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM