JavaFX TextField cancelEdit无法按预期工作 [英] JavaFX TextField cancelEdit not working as expected

查看:248
本文介绍了JavaFX TextField cancelEdit无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 TextField 当我按 Esc 时,我希望将该字段的内容恢复到之前的值,这是大多数系统上的预期行为(我有不知道为什么JavaFX默认不这样做)。

I have a TextField and I would like the contents of the field to be restored to their previous value when I press Esc which is expected behaviour on most systems (I have no idea why JavaFX doesn't do this by default).

为此,我尝试使用 TextField.cancelEdit() 但似乎没有做任何事情。

To this end I tried to use TextField.cancelEdit() but it appears that this is doing nothing.

这是一个SSCCE

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.stage.Stage;

public class UiTest2Controller extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage aPrimaryStage) throws Exception {
        final TextField field = new TextField();
        field.setOnAction(aEvent -> {
            System.out.println("Action");
        });
        field.setOnKeyPressed(aEvent -> {
            if (aEvent.getCode() == KeyCode.ESCAPE) {
                System.out.println("Escape");
                field.cancelEdit();
                field.getParent().requestFocus();
            }
        });
        field.setPromptText("Hello World...");

        aPrimaryStage.setScene(new Scene(new Group(field)));
        aPrimaryStage.show();
    }
}

重现步骤:


  1. 在文本字段中输入内容

  2. Esc

  1. Type something in the text field
  2. Press Esc

预期行为:该字段返回上一个值(第一次为空)并且焦点丢失。

Expected behaviour: The field returns to previous value (empty first time) and focus is lost.

实际行为:当时fiels保留其值并且焦点丢失。

Actual behaviour: The fiels retains its value at the time and focus is lost.

推荐答案

我不确定具体细节,但如果 TextField TextFormatter ,它似乎按预期工作已分配:

I am not sure about the specifics, but it seems to work as expected if the TextField has a TextFormatter assigned:

field.setTextFormatter(new TextFormatter<>(TextFormatter.IDENTITY_STRING_CONVERTER));

这篇关于JavaFX TextField cancelEdit无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆