To execute the method when the length of the text is greater than 7 this is correct, but remember that spaces can add a longer length, use trim () to remove spaces at the ends of the text:
if (txtcodigo.getText().trim().length()>7) { // mayor que 7
ticket();
}
For example, this String has a length of 8:
String s = "Dexen14 ";
int slength = s.length();
If we apply the method trim () , would have a length of 7, which is the expected value without counting the space:
String s = "Dexen14 ";
int slength = s.trim().length();
Update : the user types "17234752" and wishes that when the last digit is typed, the validation is activated, however this will activate a character later since it is calling the method KeyTyped()
You must use the method keyReleased () so that writing the character and releasing the key was called validation.
@Override
public void keyReleased(KeyEvent e) {
if (txtcodigo.getText().trim().length()>7) {
ticket();
}
}
keyReleased ( ) Invoked when a key has been released.