Question

I want to restrict user from entering Special characters in SWT text field. I tried the below code, but it is not working....

   txt_Appname.addKeyListener(new KeyAdapter()
    {
        public void keyTyped(KeyEvent e) {
            char chars = e.character;
            if (!Character.isLetterOrDigit(chars)) {
                e.doit = false;
                return;
            }
        }
    });

can any one give me the working code for restricting special characters in SWT textfield ?

Was it helpful?

Solution

Use a VerifyListener:

txt_Appname.addVerifyListener(new VerifyListener() {
  @Override
  public void verifyText(VerifyEvent e) {
      String text = e.text;
      for (int i = 0; i < text.length(); i++) {
         if (!Character.isLetterOrDigit(text.charAt(i)) {
            e.doit = false;
            return;
         }
      }
  }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top