7 Replies Latest reply on Sep 24, 2012 7:00 AM by Jörg

    JFormattedTextField looses document

      Hi, I have a class "BADTextField" that extends JFormattedTextField, and a class "BADDocument" that extends PlainDocument
      I want to limit the number of characters in the JFormattedTextField using the Document.

      I have this in my BADTextField that is called during construction
      private void setLengthLimit(final Integer lengthLimit) {
              if (lengthLimit != null) {
                  setDocument(new BADDocument(lengthLimit));
      Here is my BADDocument
      package dk.steria.exp.client.components;
      import javax.swing.text.AttributeSet;
      import javax.swing.text.BadLocationException;
      import javax.swing.text.PlainDocument;
      public class BADDocument extends PlainDocument {
          private static final long serialVersionUID = 1L;
          private int limit;
          public BADDocument(int limit) {
              setLimit(limit); // store the limit    
          public final int getLimit() {
              return limit;
          public void insertString(int offset, String s, AttributeSet attributeSet) throws BadLocationException {
              if (s == null)
              if (offset < limit) {
                  super.insertString(offset, s, attributeSet);
              } else
          public final void setLimit(int newValue) {
              this.limit = newValue;
      When I start my Swing application it sometimes work, but after navigating the input fields it suddenly does not work. It it like the Document disappears from the JFormattedTextField. I can't seem to find a pattern for when it works and when it stops working.

      Anyone had the same or similar problem ?

      Edited by: Kristian Lind on Sep 19, 2012 3:15 PM