1

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.!!

nIcE cOw
  • 24,468
  • 7
  • 50
  • 143

1 Answers1

2
  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
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • example for the KeyBindings, which i can refer for my problem. to check whether input is alphabet or not. –  Feb 20 '12 at 17:59
  • use DocumentListener, and you have to forgot thinking about KeyBindings for JTextComponents – mKorbel Feb 20 '12 at 18:09
  • i found the help for KeyBindings, http://stackoverflow.com/questions/7976209/using-keybinding-to-get-keycode, but i don't think so, it will solve my problem. –  Feb 20 '12 at 18:09