【发布时间】:2012-10-11 21:57:57
【问题描述】:
我试图检查用户在文本框中输入字符时是否为数字。如果不是,则应立即将其从文本框中删除。
发生的情况是我输入数字 1(或任何数字或字符),当它显然是数字时,它会从文本框中删除该值。
这是我正在使用的事件:
private void txtLengthAKeyReleased(java.awt.event.KeyEvent evt) {
removeLastChar(txtLengthA); //pass the textbox
}
这里是 removeLastChar() 方法:
public static void removeLastChar(JTextField txt)
{
//Get string from text field
String str = txt.getText();
//Make sure length > 0
if( (str.length()) != 0)
{
//Get the last char of the string
String s = str.substring(str.length()-1, str.length()-1);
System.out.println(s); //test debug
//If not numeric (try/catch Double.parseDouble)
if(!isNumeric(s));
{
//Remove last char from the text box
str = str.substring(0, str.length()-1);
txt.setText(str);
}
}
}
检查字符串是否为数字:
isNumeric() function:
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
【问题讨论】:
-
请看一下这个thread,回答这个问题以及关闭它的原因可以让你很好地了解如何解决这种情况:-) KeyEvents 对于 Swing 而言级别太低,请改用 DocumentFilter,如某些答案和该链接中所述。
-
啊,我怕你们这么说。
标签: java swing events textbox numeric