Cómo restringir el JTextField a una x cantidad de caracteres
Tengo que restringir el número de caracteres en JTextField. Utilicé el siguiente código para hacerlo, pero el problema es que estoy alimentando los datos a JTextField usando el teclado virtual. Por lo tanto, el desplazamiento se establece en 0 todo el tiempo. Cuando ingreso más de la cantidad de caracteres especificada, restablece el campo y empiezo a hacerlo desde el principio. Por ejemplo, si mi límite es de 3 caracteres y estoy ingresandoxyz0
mi cuadro de texto limitado lee el carácter hastaz
y luego borra el campo y reinicia nuevamente. Así que me quedo con0
en el campo. El código es el siguiente
public class JTextFieldLimit extends PlainDocument {
private int limit;
public JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
@Override
public void insertString( int offset, String str, AttributeSet attr ) throws BadLocationException {
if (str == null) return;
System.out.println("from document helper getLength():"+getLength());
System.out.println("from document helper str.length():"+str.length());
System.out.println("from document helper str:"+str);
System.out.println("from document helper attr:"+attr);
System.out.println("from document helper offset:"+offset);
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}