我是 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 http://docs.oracle.com/javase/7/docs/api/javax/swing/JFormattedTextField.html反而。
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 http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html有关自定义格式的链接。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)