gpt4 book ai didi

java - 使用 Java (Netbeans) 中的 JTextfield 使用点分隔符使输入字段自动格式化数字

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:52:20 26 4
gpt4 key购买 nike

我是 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);

Here's关于自定义格式的链接。

关于java - 使用 Java (Netbeans) 中的 JTextfield 使用点分隔符使输入字段自动格式化数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16686339/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com