JApplet - 不允许使用字母

时间:2012-02-20 17:30:57

标签: java swing validation japplet

这是我的代码,它写在我的applet

KeyListener keyListener = new KeyListener() 
{
    public void keyPressed(KeyEvent keyEvent) 
    {
        validate valid=new validate();
        valid.errorMessage(txt_district_id, keyEvent);
    }

    public void keyReleased(KeyEvent keyEvent) 
    {       
    }

    public void keyTyped(KeyEvent keyEvent) 
    {       
    }

};
txt_district_id.addKeyListener(keyListener);

验证类的代码是

public class validate
{
    public String errorMessage(KeyEvent keyEvent,JTextField txt)
    {
        int keyCode = keyEvent.getKeyCode();
        String keyText = KeyEvent.getKeyText(keyCode);
        //msg.setText(title + " : " + keyText + " / " + keyEvent.getKeyChar());
        if(keyCode > 47 && keyCode < 58)
        {
            txt.setEditable(true);
        }
        else
        {
            txt.setEditable(false);
            return "Only Numeric Value Accepted";
        }
    }
}

一切正常,但问题是每当用户输入任何字母时,文本字段将被禁用,这就是我的问题。我的意思是它应该,不能输入字母表,并且在任何情况下都应该启用textfield。在此先感谢。!!

1 个答案:

答案 0 :(得分:2)

  1. DocumentListener
  2. 中使用JTextComponents进行收听更改
  3. 请勿使用KeyListener,此Listener指定用于史前AWT组件,Swing JComponentsJApplet)使用KeyBindings