There are many questions about the use of these functions and events here clarify the doubts. However there are many ways to achieve this limitation.
There are many questions about the use of these functions and events here clarify the doubts. However there are many ways to achieve this limitation.
The way to give a character restriction for example to a DNI or RUT in a JTextField would come like this:
public void maxdni(KeyEvent e, JTextField txtDni, int longitud){
if (txtDni.getText().length() >= longitud)
e.consume();
}
protected void keyTypedTxtDni(KeyEvent arg0) {
maxdni(arg0, txtDni, 8);
}
I have two non-return functions that validate me the number of characters I need to enter. The KeyTyped and KeyEvent events allow me to assign the size and JTextField chosen, with the function .consume () it will erase all the other characters entered.
You can also use regular expressions, for example for a dni you can use:
String regex = "\d{8}[A-HJ-NP-TV-Z]";
Pattern.matches(regex, dni)
is also used, which returns true or false depending on whether the dni that is entered as the second parameter complies with the regular expression that is passed as the first parameter.