2

How can I format the content of a text field while the user is typing. Specifically, I want to add thousand separators to numbers.

(What to do in case of invalid/non-numeric input? Ideally, the formatting would simply not be applied. But it would also be an acceptable solution to me to prevent invalid input in the first place - if there is a good way to do that!)

I've searched for a solution of this problem for a long time and tried lots of examples, but none of the existing answers (e.g. Question about JTextField and text format with numbers?) are satisfying.

Thanks a lot!

Community
  • 1
  • 1
MonitorLizard
  • 147
  • 1
  • 11

1 Answers1

1

Java's controls don't do this very well by default. I recommend using something like ImprovedFormattedTextField, which is documented very well in this post:

Is there any way to accept only numeric values in a JTextField?

Your question is not exactly a duplicate, but you should be able to adapt the class to work as you expect. The background will turn red if the number is not formatted correctly.

Community
  • 1
  • 1
durron597
  • 31,968
  • 17
  • 99
  • 158
  • My question is not primarily about preventing invalid input. I'm interested in formatting (adding thousand separators). I think this cannot be done using an `ImprovedFormattedTextField`. In the example they use a property change listener to change some external component or an attribute. However, changing the text itself would cause an infinite recursion – MonitorLizard Apr 17 '15 at 16:29