Como restringir o JTextField a um número x de caracteres

Preciso restringir o número de caracteres no JTextField. Usei o código a seguir para fazer isso, mas o problema é que estou alimentando os dados no JTextField usando o teclado virtual. Portanto, o deslocamento é definido como 0 o tempo todo. Quando insiro mais do que o número especificado de caracteres, ele redefine o campo e começa a fazê-lo desde o início. Por exemplo, se meu limite é de 3 caracteres e eu estou inserindoxyz0 minha caixa de texto limitada lê o caractere atéz e, em seguida, limpa o campo e reinicia novamente. Então, eu sou deixado com0 no campo. O código é o seguinte.

  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);  
    }  
  }  
}  

questionAnswers(1)

yourAnswerToTheQuestion