JavaFX TextField cancelEdit not working properly

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 on most systems (I don't know why JavaFX does not do this by default).

To this end, I tried using TextField.cancelEdit() , but it seems like it does nothing.

Here is 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(); } } 

Steps to play:

  • Enter text in the text box.
  • Press Esc

Expected behavior: The field returns to the previous value (empty at first), and the focus is lost.

Actual behavior: The fillet retains its value at that time, and focus is lost.

+2
source share
1 answer

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

 field.setTextFormatter(new TextFormatter<>(TextFormatter.IDENTITY_STRING_CONVERTER)); 
+4
source

All Articles