jTextField is not updated with keyboard event

0

Good, I try to make a field where I can not write numbers, just alpha characters [a-zA-Z] in a jTextField. What I want is that when you type letters that comply with this, they are placed in the textField and if they are number or something else they are not placed, or at least they are updated to erase it, my code is as follows:

 public void keyPressed(KeyEvent e) {
    char keyCode = e.getKeyChar();  //obtenemos el codigo de la tecla 
    String keyText = String.valueOf(keyCode);  //luego el caracter 
    System.out.println(cadena);
    System.out.println("Tecla digitada: " + keyText);
    try {
        escribir(keyText);
    } catch (MyException ex) {
        System.out.println(ex.getMessage());
    }
}

private void escribir(String a) throws MyException {  
//Pattern pat1 = Pattern.compile("[0-9]*");  
    Pattern pat2 = Pattern.compile("[a-zA-Z]");  
    Matcher mat = pat2.matcher(a);  
    if (mat.matches()) {  
        cadena = cadena + a;  
        System.out.println(cadena);  
    } else {  
        throw new MyException("Caracteres no permitidos, solo [A-Z], [a-z]");  
    }  
    jTextField1.setText(cadena);  
}  

But nevertheless the textfield continues to write any character, as they try to set the text every time the keyPressed event is executed but this does not happen, it places the letters but the string is correct, it does not accept anything that is not alphabetic.

Messages are from the catch when it catches the exception it creates.

    
asked by Parzival 18.05.2017 в 06:23
source

1 answer

0

The problem is where you have placed the string writes (the jTextField1.setText(cadena); ). Where you are currently, you will always write the text, whether you enter letters or another character. This string should be written as long as the condition you are using is met, it would look like this:

if (mat.matches()) { 
    cadena = cadena + a;
    System.out.println(cadena);
    jTextField1.setText(cadena);
}else{
    //...
    
answered by 18.05.2017 в 06:46