1

I tried this, but the JTextField keeps showing the last key entered. What I'm I doing wrong?...

private void codigoKeyTyped(java.awt.event.KeyEvent evt) {
    //codigo is the JTextField
    String s = String.valueOf(evt.getKeyChar());
    try{
        Integer.parseInt(s);
    }catch(Exception e){
        codigo.setText("");    
    }
}

Lastly, I want it to delete the last character and leave the integer value in the text field. But I guess that would be simple after solving that. Thanks!

//ANSWER!

Thanks everybody to answer my question. Finally I made this

private void codigoKeyTyped(java.awt.event.KeyEvent evt) {

    char c = evt.getKeyChar();

    if (! Character.isDigit(c)) {
        evt.consume();            
    }
}
Roger
  • 2,912
  • 2
  • 31
  • 39
  • Thanks! I speak Spanish, so, I mistake a lot... Sorry, and thanks!! – Roger Sep 08 '10 at 00:50
  • 1
    Are you aware that listening for KeyEvents won't work in all cases? There are other input methods too. You should always use DocumentListener if you want to be notified of changes to the text. And like Tom said, in this case DocumentFilter is the right way to go. – Carlos Sep 10 '10 at 15:30
  • Yes, I'm aware of that, but, this is just a simple work for my classes and this is enough (this is just for a JTextField with no more than 5 characters, I don't put all the code here)... however I will learn how to use DocumentFilters because it seems to be the best way to do it. I'm totally new at Java (for about two weeks) and in programming (6 months), so, I don't make things on its best expression. I hope some day I will. Thanks for answering! – Roger Sep 10 '10 at 20:25

3 Answers3

2

I'd suggest using a DocumentListener intead. See this example for sample code.

Catchwa
  • 5,845
  • 4
  • 31
  • 57
1

Using a key listener (or even document listener) is inappropriate for this task. Arguably the listener model is inappropriate for input events. Do you expect your listener code to run before or after the listener code that inserts the key value? How are you going to handle copy-and-paste key strokes, and also mouse driven drag-and-drop?

The way to handle this is with a DocumentFilter.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
-2

You've got to read your JTextField once the user is ready to do something... for example, clicking an "OK" button. Create such a button and place the following code in its ActionPerformed method:

String idtxt = codigo.getText();

int id = Integer.parseInt(idtxt);

Currently, your JTextField read is triggered by a KeyEvent, with evt.getKeyChar() returning the key that was pressed. That event is good perhaps for making a "clicky" noise, but won't work for ints > one digit!

Pete
  • 16,534
  • 9
  • 40
  • 54