2

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Valentino Ru
  • 4,964
  • 12
  • 43
  • 78
  • Hopefully this [answer](http://stackoverflow.com/a/9478124/1057230) might can help you on the topic or this [answer](http://stackoverflow.com/a/5663094/1057230) – nIcE cOw Oct 14 '12 at 04:41

2 Answers2

2

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.

Robin
  • 36,233
  • 5
  • 47
  • 99
  • But I have to react on every new appended single number, is this possible? Like I type in a 1 -> make something with that 1, as soon as I type a further 1 -> make something with the 11. So I think you mean that I always take the whole number that is written in the textfield instead of "building" the number? Is it possible (I think with the JFormattedTextField) to allow only number input? – Valentino Ru Oct 13 '12 at 15:39
2

I think that having an error message to show each time the user presses anything but an integer is a bit annoying. Check this sample code that uses a regular expression to match the input and has the advantage of accepting only digits, anything else is just not inserted to the textfield (managed by overriding the insertString method of PlainDocument).

Rempelos
  • 1,220
  • 10
  • 18