JavaFX: Prevent TextField auto-selection on refocus

JavaFX punched me in the face with a feature which I consider as a kind of general over-assumption and as a bug in The Console. When TextField is refocused through other event than click then it auto selects it’s whole content. I want my previous selection or caret position.

A workaround/hack/fix is introduced in this post. Oh, by the way, there’s a bug report.

The Bug

As I noted, JavaFX team doesn’t consider this as a bug. It’s rather a feature which I don’t want to have turned on but don’t have a choice about it.

TextField performs automatic text selection of it’s content in following situations (in my app):

  • hit TAB key on Console Output
  • manual requestFocus() call

The Solution

Algorithm:

  1. When focus is lost, remember selection/caret positions.
  2. When focus regained, simply bring back selection/caret positions.

However! Automatic selection (the bug) occurs after focus event handler is being executed which is why we need to defer state reloading. To make the delay as shortest as possible, simply run the code inside Platform#runLater().

References