Lambros
Lambros

Reputation: 151

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

Upvotes: 2

Views: 652

Answers (3)

Levenal
Levenal

Reputation: 3806

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();
               }

Upvotes: 3

mKorbel
mKorbel

Reputation: 109815

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.

Upvotes: 4

Alowaniak
Alowaniak

Reputation: 600

You'll get the event before it's handled by the TextField. What you can do is consume the event, that way the TextField won't receive it.

(A better approach might be a DocumentFilter, you can still copy-paste numbers into the TextField with the KeyListener.)

Upvotes: 3

Related Questions