Create and use custom PlainDocument for JTextField - Java Swing

Java examples for Swing:JTextField

Description

Create and use custom PlainDocument for JTextField

Demo Code

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;

public class Main {

  public static void main(String[] args) {
    Document tenCharDoc = new LimitedCharDocument(10);
    JTextField t1 = new JTextField(tenCharDoc, "your name", 10);
  }/*from   w w  w.  j  a  va2  s. com*/
}

class TenCharTextField extends JTextField {
  @Override
  protected Document createDefaultModel() {
    return new LimitedCharDocument(10);
  }
}
class LimitedCharDocument extends PlainDocument {
  private int limit = -1; // < 0 means an unlimited characters

  public LimitedCharDocument() {
  }
  public LimitedCharDocument(int limit) {
    this.limit = limit;
  }

  @Override
  public void insertString(int offset, String str, AttributeSet a)
      throws BadLocationException {
    String newString = str;
    if (limit >= 0 && str != null) {
      int currentLength = this.getLength();
      int newTextLength = str.length();
      if (currentLength + newTextLength > limit) {
        newString = str.substring(0, limit - currentLength);
      }
    }

    super.insertString(offset, newString, a);
  }
}

Related Tutorials