我有一个JTextField,用户必须输入数字。
我想检查一下这个值,以确保它包含* *整数* 。 *
以下是代码:
JTextField Tex_amount=new JTextField();
.
.
.
String s=Tex_amount.getText();
int a=Integer.parseInt(s);
问题是如果用户在我将面临错误的字段中输入字符串: 的 java.lang.NumberFormatException 即可。那我怎么检查价值?
答案 0 :(得分:7)
有三种方式
将JFormattedTextField与Number Formatter一起使用
将JSpinner与SpinnerNumberModel一起使用
将DocumentFilter添加到普通的JTextField
答案 1 :(得分:3)
您可以使用try..catch
try{
int a = Integer.parseInt(s);
}
catch(ArithmeticException e){
//Handel error here
}