2

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.

hungr
  • 2,086
  • 1
  • 20
  • 33
  • 1
    This may give you some clues/ideas: http://stackoverflow.com/questions/1320117/why-is-jformattedtextfield-evil – Yasin Okumuş Sep 09 '11 at 02:24
  • 1
    Some related examples may be found [here](http://stackoverflow.com/questions/6803976/focusevent-doesnt-get-the-last-value-of-jformattedtextfield-how-i-can-get-it) and [here](http://download.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html). – trashgod Sep 09 '11 at 02:30
  • *"Now I need to make an applet.."* Do you *really* need an applet, or just a Java app. that can be launched from a link? – Andrew Thompson Sep 09 '11 at 02:54
  • @ Andrew Thompson: Not necessary to be an applet, just a java app using swing will be fine. – hungr Sep 09 '11 at 02:56

1 Answers1

3

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.

Catchwa
  • 5,845
  • 4
  • 31
  • 57
  • Thanks for your answer, but inside the DocumentListener api documentation, it mentioned that : "Document listeners should not modify the contents of the document; The change is already complete by the time the listener is notified of the change. Instead, write a custom document that overrides the insertString or remove methods, or both. See Listening for Changes on a Document for details." I think i will go for creating a custom document and try with that =] – hungr Sep 12 '11 at 04:25