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.