Your code is problematic in several respects. First of all, you're changing the text of the input field while the user is still typing. This makes for an awful user experience, since the user has to take great care that he is not disrupting the number format you plant on him while typing. Otherwise, your formatting algorithm would break.
Then, you don't take into account that the text you get from the TextChangeEvent
has already been formatted when the text already has some length. That is, when the user typed '10', your text field displays '10,'. When the user then types 3 more numbers, e.g. '10,123', your algorithm takes that String and adds a decimal point to the right, yielding '10,123.' This is why you end up with your number format reversed.
That said, you should really not cobble together a formatted number String like that. Readers of your code (which might be your future self) will stare blankly at your code and try to make out what you're trying to achieve.
A way better solution is to use an instance of java.text.NumberFormat
to do the formatting for you. Then you should not change the value of the text field while the user is typing. Better put the output of the NumberFormat
into a label that is displayed next to or below the MoneyField. After each TextChangeEvent
you can feed the current input text to the NumberFormat
anew.
As a tip regarding handling money values, you might want to take a look at the Joda-Money library. There's a lot one can do wrong with money amounts ;)