Reputation: 151
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
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
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.
KeyListener isn't proper Listener
for Swing JComponents
, nor for JTextComponents
use DocumentFilter for plain vanilla JTextField
use JFormattedTextField with Number Formatter
JOptionPane inside events fired from listener must be wrapped into invokeLater
Upvotes: 4