Search code examples
javanetbeansadditionseparator

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


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.


Solution

  • 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.