如何使JFormattedTextField接受不带小数点的整数(逗号)? [英] How to make JFormattedTextField accept integer without decimal point (comma)?
问题描述
我以这种方式使用 JFormattedTextField
与 NumberFormat
:
-Creat a JFormattedTextField
refernce
-Creat a JFormattedTextField
refernce
JFormattedTextField integerField;
创建一个 NumberFormat
引用
NumberFormat integerFieldFormatter;
- 在构造函数中:
-In the constructor:
integerFieldFormatter = NumberFormat.getIntegerInstance();
integerFieldFormatter.setMaximumFractionDigits(0);
integerField = new JFormattedTextField(integerFieldFormatter );
integerField.setColumns(5);
..........
..........
我的意思是只使用整数,但是当我键入1500这样的数字时,它会在失去焦点后转换为1,500,抛出异常就是它的第一行:
I meant to use it with integer numbers only, but when I type numbers like 1500 it is converted after losing focus to 1,500 , and exception thrown this is the first line of it:
线程中的异常AWT-EventQueue-0
java.lang.NumberFormatException:对于输入字符串:1,500
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "1,500"
当我使用 JTextField
而不是 JFormattedTextField
所有正常接受的整数,但我之所以想使用 JFormattedTextField
,是因为它的输入限制优势。
When I use JTextField
instead of JFormattedTextField
All integers accepted normally, But the reason why I want to use JFormattedTextField
is to benefit from its input restriction advantages.
推荐答案
我发现了解决问题的方法; 这里它是:
I discovered the solution to my problem; Here it is:
确切的问题是当我使用 JFormattedTextField
时带 NumberFormat
,JFormattedTextField 添加逗号','在任何接下来的3位数之前,例如
The exact problem is that when I use JFormattedTextField
with NumberFormat
, the JFormattedTextField adds comma ',' before any next 3 digits for example
1000呈现为1,000
1000 rendered as 1,000
10000呈现为10,000
10000 rendered as 10,000
1000000呈现为1,000,000
1000000 rendered as 1,000,000
当我从JFormattedTextField读取整数值时,请使用以下代码行
When I read an integer value from JFormattedTextField usign this line of code
int intValue = Integer.parseInt(integerField.getText());
逗号作为字符串的一部分读取; 1000读为1,000并且此字符串值无法转换为整数值,因此抛出异常。
The comma is read as part of the string; 1000 read as 1,000 and this string value cannot be converted to integer value, and so exception is thrown.
老实说解决方案是在答案但我会在这里重复一遍
Honestly the solution is in this Answer but I will repeat it here
使用 str.replaceAll( ,,)
int intValue = Integer.parseInt(integerField.getText().replaceAll(",", ""));
这将取代任何逗号charachter ','
在返回的字符串中,将按预期正常转换为 int
。
This will replace any comma charachter ','
in the returned string and will be converted normally to int
as expected.
问候
这篇关于如何使JFormattedTextField接受不带小数点的整数(逗号)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!