我以这种方式将 JFormattedTextField
与 NumberFormat
一起使用:
-创建一个JFormattedTextField
引用
JFormattedTextField integerField;
-创建一个NumberFormat
引用
NumberFormat integerFieldFormatter;
-在构造函数中:
integerFieldFormatter = NumberFormat.getIntegerInstance();
integerFieldFormatter.setMaximumFractionDigits(0);
integerField = new JFormattedTextField(integerFieldFormatter );
integerField.setColumns(5);
..........
我打算只将它用于整数,但是当我输入像 1500 这样的数字时,它会在失去焦点后转换为 1,500 ,并抛出异常这是它的第一行:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "1,500"
当我使用 JTextField
而不是 JFormattedTextField
时,所有的整数都正常接受,但是我之所以要使用 JFormattedTextField
是为了受益于它输入限制优势。
最佳答案
我意识到这是一个老问题,但我只是通过同样的问题偶然发现了它。由于其他答案对我来说似乎是解决方法,所以我仔细研究了 NumberFormat 方法。
我发现最简单的方法实际上是简单地停用 NumberFormat 实例上的分组:
NumberFormat integerFieldFormatter = NumberFormat.getIntegerInstance();
integerFieldFormatter.setGroupingUsed(false);
这样,文本字段输出中就不会出现组定界符。
当然你也不能将它们用于你的输入,但这不是问题的意图,对吧?
此外,对于 NumberFormat 的整数实例,您不需要显式设置 MaximumFractionDigits(0),因为这是 getIntegerInstance() 为您所做的一部分。
关于java - 如何使 JFormattedTextField 接受不带小数点(逗号)的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14467858/