问题描述
我有一个当我按时,我希望将该字段的内容恢复到之前的值,这是大多数系统上的预期行为(我有不知道为什么JavaFX默认不这样做)。
I have a TextField
and I would like the contents of the field to be restored to their previous value when I press which is expected behaviour on most systems (I have no idea why JavaFX doesn't do this by default).
为此,我尝试使用但似乎没有做任何事情。
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();
}
}
重现步骤:
- 在文本字段中输入内容
- 按
- Type something in the text field
- Press
预期行为:该字段返回上一个值(第一次为空)并且焦点丢失。
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无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!