Search code examples
javaswingjtextfieldkeylistenerjoptionpane

JTextField Keylistener can't erase input


I have a JTextField that works perfectly fine when someone enters a number instead of a letter. My only problem is that that the number then does not dissappear. The user can't enter any other numbers but that last number pressed stays always in the filed! Why?

    searchF.addKeyListener(new KeyAdapter(){
            public void keyTyped(KeyEvent e){
                char ch = e.getKeyChar();
                if(Character.isDigit(ch)){
                    searchF.setText(" ");
                    JOptionPane.showMessageDialog(null, "Please Enter Only Names or Surnames. Letters Only Allowed");
                    searchF.setText(" ");
                   }
               }
 });

Solution

  • This is another way of coming at the issue, Consume the key event if it is a number, that way the user doesn't lose their input but you still get the message.

      if(Character.isDigit(ch)){
                    JOptionPane.showMessageDialog(null, "Please Enter Only Names or Surnames. Letters Only Allowed");
                 e.consume();
                   }