我是Java新手在我的第一个Java程序(使用Netbeans),我想添加输入字段自动格式数字与点"。"分隔符使用JTextfield。以下是我的简短代码:
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);
}
但是我觉得不够完美,因为插入符号/光标不能通过键盘上的箭头键移动。我试着寻找更好的代码,但我从来没有找到它。有人有解决方案吗?谢谢。
您应该使用JFormattedTextField
。
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);
这里有一个关于自定义格式的链接
更改区域设置
在ENGLISH
中,千位分隔符为,
,小数点分隔符为.
。在大陆语言中,如FRENCH
,这是另一种方式。
您还可以使用NumberFormat
以语言环境感知的方式解析数字。你不需要做任何替换