hungr
hungr

Reputation: 2096

About auto formatting numbers in java swing

Now I need to make an applet and make use of JTextField or JFormattedTextField which is for user to input numbers. I would like to ask how to automatically format the input number dynamically during user input just like what normal calculator do?

For example: When the user enters 1000, the display in JTextField/JFormattedTextField will be 1,000 and when the user continue to input one zero digit, then the display will be 10,000

Thank you.

Upvotes: 2

Views: 562

Answers (1)

Catchwa
Catchwa

Reputation: 5855

If you want the comma to be placed/removed while the user is still editing the JTextField you can't use a PropertyChangedListener as the event is only triggered when the field loses focus or the user hits the enter key (from @trashgod's link).

If you use a DocumentListener instead, you can capture insertUpdate and removeUpdate events which happen as the user is typing. When you capture these events, write some code that will start at the first digit to the left of the decimal point and remove/insert commas as necessary.

Upvotes: 3

Related Questions