views:

76

answers:

3

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

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
+2  A: 

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

Catchwa
+1  A: 

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. The use of this is demonstrated in my trivial Swing example blog entry.

Tom Hawtin - tackline