JTextField 클래스를 이용하면 간단하게 텍스트 입력 필드를 화면에 뿌려줄 수 있다. 그런데 JTextField 자체에는 입력 글자수를 제한하는 메써드가 존재하지 않는다. 즉, 10자 까지만 입력하게 하고 싶어도 기본 API로는 구현이 불가능하다. 입력 할 글자수를 제한하려면 다음과 같이 PlainDocument 클래스를 상속받은 클래스를 정의하여 구현할 수 있다.
public class JTextFieldLimit extends PlainDocument 
{
private int limit; // 제한할 길이
public JTextFieldLimit(int limit) // 생성자 : 제한할 길이를 인자로 받음
{
super();
this.limit = limit;
}
// 텍스트 필드를 채우는 메써드 : 오버라이드
      public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException 
      {
            if (str == null)
                  return;
            if (getLength() + str.length() <= limit) 
                  super.insertString(offset, str, attr);
       }
}
사용법은 다음과 같다.
textfield.setDocument(new JTextFieldLimit(10));