用于检查的Java TextBox KeyReleased事件isNumeric()

时间:2012-10-22 05:41:47

标签: java swing events textbox numeric

我试图检查用户在文本框中键入字符的时间是否为数字。如果不是,则应立即将其从文本框中删除。

我输入的数字是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;  
    }

3 个答案:

答案 0 :(得分:1)

使用KeyListeners过滤或修改JTextComponets只会以泪流满面。

您应该使用DocumentFilter

查看Limit the Characters in the text field using document listnerDeleting last keystroke in JTextField if invalidJTextField limiting character amount input and accepting numeric only的示例(特别是上一个问题中答案中的链接)

答案 1 :(得分:1)

如果用户在文本字段的中间键入非数字字符,会发生什么?还是刚开始?

您可以使用DocumentFilter实现更好的解决方案: http://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#filter

当您确定要插入或替换的字符串有效时,您只需要调用super.insert .... (在你的情况下是数字)。

答案 2 :(得分:0)

应该是

        String s = str.substring(str.length()-1, str.length();

使用您的代码,s的值始终为空字符串。

要测试单个字符是否为数字,请使用

Character.isDigit(str.substring(0,1))