JApplet - 不允许使用字母表

发布于 2025-01-07 13:26:25 字数 1086 浏览 3 评论 0原文

这是我的代码,写在我的小程序中

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";
        }
    }
}

一切正常,但问题是每当用户输入任何字母时,文本字段就会被禁用,这就是我的问题。我的意思是,无论如何都不能输入字母表,并且应该启用文本字段。提前致谢。!!

this is my code, which is written inside my 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);

and code of validate class is

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";
        }
    }
}

everything working properly, but the problem is whenever user input any alphabet the textfield will become disable, and that is my problem. I mean it should like, alphabet can not be entered and textfield should be enabled in any case. Thanks in advance.!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

扬花落满肩 2025-01-14 13:26:25
  1. 使用 DocumentListener 监听 JTextComponents
  2. 不要使用 KeyListener,这个Listener是为史前指定的AWT 组件,用于 Swing JComponents (JApplet) 使用 按键绑定
  1. Use DocumentListener for listening changes inside JTextComponents,
  2. Don't use KeyListener, this Listener is designated for prehistoric AWT Components, for Swing JComponents (JApplet) use KeyBindings
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文