Reputation: 83
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.
Upvotes: 3
Views: 8617
Reputation: 61168
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.
Upvotes: 1
Reputation: 93872
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.
Upvotes: 4