3

I writing an application using Swing. My application has a text box and what I want to do is this: when user enters a number in that text field, if the number is in the thousands, then it is automatically appended a comma in the number. For example, if user enters 1000, then it should be automatically changed to 1,000, or 1,000,000 or so.

Does anyone give me some ideas, please?

jzd
  • 23,473
  • 9
  • 54
  • 76
ipkiss
  • 13,311
  • 33
  • 88
  • 123

3 Answers3

4

Try formattedTextFields

Also one more example. May be helpful to you.

Harry Joy
  • 58,650
  • 30
  • 162
  • 207
3

You can use the DecimalFormat and NumberFormat classes. See an example here; http://www.exampledepot.com/egs/java.text/FormatNum.html

Update:

Example:

NumberFormat numberFormatter = new DecimalFormat("#,###,###");
String formattedNumber = numberFormatter.format(10000000);

JTextField numberTextField = new JTextField();

numberTextField.setText(formattedNumber);
Mudassir
  • 13,031
  • 8
  • 59
  • 87
  • @Mudassir: @SamG: Can we show numbers in textFields this way? It just format numbers. isn't it? – Harry Joy Mar 31 '11 at 10:16
  • @mudassir, a Formatted Text Field is a more appropriate answer for handling this in a GUI. – jzd Mar 31 '11 at 11:08
  • @Harry Joy: Yes we can show numbers in TextFields this way. See the updated answer. – Mudassir Mar 31 '11 at 11:10
  • @Mudassor: OP wants to format the number while the user typing in textField. Not like this. I know this way of doing. But this is not OP is asking as per I understand his question. But OP has accepted your answer so enjoy rep points. ;-) – Harry Joy Mar 31 '11 at 11:13
  • @Harry: I was unaware of FormattedTextFields thats why I suggested it, your way is of course best suited. – Mudassir Mar 31 '11 at 11:16
  • @Mudassir: Wish OP thinks the same. :-) – Harry Joy Mar 31 '11 at 11:23
  • @Harry: Sorry Harry, I can't uncheck that green mark. :-( But of course I can give you a +1. – Mudassir Mar 31 '11 at 11:27
2

Have a look at group seperators in DecimalFormat .

SamG
  • 646
  • 4
  • 8