I put a KeyListener
on a TextField
in my swing application to try some functionalities. The goal is to react on every key typed in that TextField
. The user should only type in numbers, but how it is, it is possible to enter alphabetical chars too. So additionally I have to check every time after a key is typed, if the whole thing is a number, if so, make something with that number, if not, tell the user there is an error without exit the program. So I want to do something like this:
String enteredNumPlayers = "";
JTextField textfieldNumPlayers = new JTextField();
textfieldNumPlayers.setBounds(/*some values*/);
textfieldNumPlayers.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.DARK_GRAY));
textfieldNumPlayers.setHorizontalAlignment(JTextField.CENTER);
textfieldNumPlayers.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
if(e.getKeyChar()!=/*Code of the back key*/){
enteredNumPlayers += e.getKeyChar();
System.out.println(e);
}else{
enteredNumPlayers = enteredNumPlayers.substring(0, s1.length()-1);
}
try{
Integer.parseInt(enteredNumPlayers);
// do something with that number
}catch (NumberFormatException err){
new ErrorDialog("Not a number"); // my own method to allude user
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
});
Now I wanted to look whats the specific Code for the back key by simply System.out.println(e)
in the keyTyped(...)
method, but following get printed:
java.awt.event.KeyEvent[KEY_TYPED,keyCode=0,keyText=Unbekannt keyCode: 0x0,keyChar=Rücktaste,keyLocation=KEY_LOCATION_UNKNOWN,rawCode=0,primaryLevelUnicode=0,scancode=0,extendedKeyCode=0x0] on (...)
why is every key value or code = 0 or unknown? Shouldn't it be the ascii value? Using "Rücktaste" would also be ugly, since on a english working computer this value would be different, isn't it? So how can I cleanly check if the key typed is the back key?
The same thing happens with other characters, except that their keyChar is the right one.
What you are looking for is a DocumentFilter
, DocumentListener
or a JFormattedTextField
. All three of them are a better solution then using a key listener as it also covers drag-and-drop, copy-paste or any other mechanism you can think of to put text into a textfield.