The TextFormatter Class in JavaFX: How to Restrict User Input in a Text Field

There are a lot of code examples for restricting or modifying user input into a JavaFX text field. Most examples I have seen suggest adding a change listener to the text field’s text property. Here’s how you would allow only lower-case characters in your text field using the change listener approach:

This approach comes with one drawback: you’ll have two events being triggered by two changes of the text property. The first change is caused by the direct user input, the second change is caused by the manipulation of the user input by the change listener. The user won’t notice these two events, but somewhere in your code you have another listener for the text property, that listener will receive two events, one with the “invalid” change and a second one with the “valid” change.

Another approach was suggested by Richard Bair a long time ago. His suggestion resulted in the TextFormatter  class being added to JavaFX with version 8u40. It’s a clean way to format, filter, or restrict user input. Here’s how it works:

What’s still missing is support for the backspace key to delete a character in the text field, but that’s just my silly example implementation. [Update 2016-12-28: The implementation was improved to support the deletion and selection of characters.]

This approach intercepts the user input before it’s written into the text property and thus fires only one event. Before that happens, you can examine and modify the Change  object in the UnaryOperator  defined in getFilter()  method.

In addition to filtering, a TextFormatter  object can convert a value to a string representation and vice versa. From the Javadoc:

A value converter and value  can be used to provide a special format that represents a value of type V. If the control is editable and the text is changed by the user, the value is then updated to correspond to the text.

Sounds pretty handy.

About the author

Uwe

Software developer with experience in Java, JavaFX, EMF, OSGi, and a little bit of Swift. I live and work in Munich.

I use this website mainly as a journal and personal knowledge data base.

My PGP key is here. There are other keys listed for me, but I use this one exclusively.

Fingerprint: 232F 05C4 01BE F43D 0434 0A8A 4ED3 5720 477E EF40

View all posts

4 Comments

  • Really nice write-up. The point about 2 change events being sent is important. And checking the characters *before* they’re sent along to textProperty seems like the right way to do things. (I’ve been looking for a good approach.) Thanks!

  • em… I tried this example code and it won’t let me delete anything I typed, or select it. I guess add backspace to list of accepted chars ? but what about the selection ?

Leave a Reply

Your email address will not be published. Required fields are marked *