3

i'm newbie in Java In my first Java program (using Netbeans) i want to add input field auto format number with dot "." separator using JTextfield. Here is my short code :

private void PayTransKeyReleased(java.awt.event.KeyEvent evt) {                                       
// TODO add your handling code here:
String b;
b = PayTrans.getText();
if (b.isEmpty()){
    b = "0";
}
else {
    b = b.replace(".","");
    b = NumberFormat.getNumberInstance(Locale.ENGLISH).format(Double.parseDouble(b));
    b = b.replace(",", ".");
}
PayTrans.setText(b);
}

But I feel less than perfect, because the caret/cursor can't move by arrow key in the keyboard. I try to search better code but I've never find it. Did anyone have the solutions? Thanks.

repot
  • 83
  • 3
  • 9

2 Answers2

4

You should use a JFormattedTextField instead.

private DecimalFormatSymbols dfs;
private DecimalFormat dFormat;

dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator('.'); //separator for the decimals
dfs.setGroupingSeparator(','); //separator for the thousands
dFormat = new DecimalFormat ("#0.##", dfs);

JFormattedTextField ftf = new JFormattedTextField(dFormat);

Here's a link about customizing the format.

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
  • Thanks, Good idea. But the results are not directly view in JFormattedTextField when I type a thousands number. The result are newly view after I move the focus to other object. – repot May 23 '13 at 02:16
  • This is how JFormattedTextField works. May you could check this link http://stackoverflow.com/questions/8383975/let-actionlistener-listen-for-change-in-jtextfield-instead-of-only-enter – Alexis C. May 23 '13 at 08:06
1

Change the locale.

In ENGLISH the thousands separator , and the decimal separator is .. In a continental language, like FRENCH, this is the other way around.

You can also parse numbers in a locale aware way with a NumberFormat. You shouldn't need to do any replacing.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166