0

I have created a form using JFormDesigner and need to add a 1000 seperator automatically when the user types a number of 4 digits or more.I have tried the following code but it does not add the seperator(,) real time.

int no=Integer.parseInt(textField1.getText());
String str = String.format("%,d", no);
textField1.setText(str);

Any help would be appreciated.

Frederic Close
  • 9,389
  • 6
  • 56
  • 67
user2723764
  • 25
  • 1
  • 2
  • 6

5 Answers5

0

Since you mentioned that it does not add the seperator in real time, then I suspect that you are executing that code upon the click of a button or something similar.

What you would need to do, would be to capture key stroke events and modify the text accordingly. This previous SO post should point you in the right direction.

Community
  • 1
  • 1
npinti
  • 51,780
  • 5
  • 72
  • 96
0

You should use DecimalFormat class to add , in number. like

 DecimalFormat df=new DecimalFormat("###,###");     

 int no=Integer.parseInt(textField1.getText());
 String str = df.format(no);
 textField1.setText(str);
Masudul
  • 21,823
  • 5
  • 43
  • 58
  • Thanks Masud.Where should I put the above code to display it real time? I'm new to java ,can't figure it out. I need to display 1000 as 1,000. – user2723764 Oct 23 '13 at 08:50
  • @user2723764 You should display it on textField1. Look at my edited answer. – Masudul Oct 23 '13 at 09:37
0

Swing has formatted text fields for this purpose - I think you're looking for JFormattedTextField

Tim Boudreau
  • 1,741
  • 11
  • 13
0

I guess you can use this

 DecimalFormat df = new DecimalFormat("#,###,##0.00");
 df.format(no);
Apostolos
  • 10,033
  • 5
  • 24
  • 39
0

To get custom grouping separator such as space, do this:

DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
symbols.setGroupingSeparator(' ');

DecimalFormat formatter = new DecimalFormat("###,###.##", symbols);
System.out.println(formatter.format(bd.longValue()));
Monicka Akilan
  • 1,501
  • 5
  • 19
  • 42