How to limit a JTextField in Java? [duplicate]

1

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.

    
asked by H4NS3L 13.11.2018 в 16:31
source

2 answers

1

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.

    
answered by 13.11.2018 в 16:31
0

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.

    
answered by 13.11.2018 в 16:43