Make input field auto format number with dot separator using JTextfield in Java (Netbeans)

StackOverflow https://stackoverflow.com/questions/16686339

  •  30-05-2022
  •  | 
  •  

문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top