开发者

Which is the best way to validate data in a JTextField?

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


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


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.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜