1

Whenever I press backspace in the text box this code is triggered.

private void txtAgeKeyTyped(java.awt.event.KeyEvent evt) {                                
        char agetext= evt.getKeyChar();
        if(!(Character.isDigit(agetext))){
            evt.consume();
            JOptionPane.showMessageDialog(null,"Age is only written in Numbers!");
        }
}

It should only be triggered if I typed Alphabets instead of Numbers only.

For some reason it is triggering whenever I press the Backspace Key.

Is there a way for me to use backspace without triggering this block of code?

I'm sorry this is the first time i fiddled with Key Events

  • What method is it? Why is it triggering? Please, add some details to your question! – Ihor Dobrovolskyi Jul 08 '17 at 17:56
  • https://stackoverflow.com/questions/15693904/java-keylistener-keytyped-backspace-esc-as-input – Yosef Weiner Jul 08 '17 at 18:00
  • if i want to delete characters using backspace in textbox the message "age is only written in numbers!" appears i used KeyTyped in Netbeans – user3647634 Jul 08 '17 at 18:01
  • @user3647634 well is the backspace key considered a digit? No, it is not. That's why your if statement evaluates to true and you see "*age is only written in numbers!*". – Jonny Henly Jul 08 '17 at 18:08
  • @JonnyHenly I think the OP knew that already. That's why he/she is trying to make backspace not trigger the method. – Sweeper Jul 08 '17 at 18:11
  • Use [`Character.isLetter(...)`](https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#isLetter(char)) instead of `isDigit(...)` and remove the leading negation from the if staement. So `if(!(Character.isDigit(agetext)))` becomes `if(Character.isLetter(agetext)))`. – Jonny Henly Jul 08 '17 at 18:12

1 Answers1

4

The backspace character is just \b. As you can see, the VK_BACK_SPACE constant is defined like this:

public static final int VK_BACK_SPACE     = '\b';

The constant is defined in the java.awt.event.KeyEvent class btw. If you use IntelliJ it will automatically and statically import it for you.

You can check whether agetext is \b. If it is, return from the method:

private void txtAgeKeyTyped(java.awt.event.KeyEvent evt) {   
    char agetext= evt.getKeyChar();
    if (agetext == VK_BACK_SPACE) return;
    if(!(Character.isDigit(agetext))){
        evt.consume();
        JOptionPane.showMessageDialog(null,"Age is only written in Numbers!");
    }
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313