Limit JTextField input to a maximum length : Document « Swing Event « Java Tutorial

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

class JTextFieldLimit extends PlainDocument {
  private int limit;

  JTextFieldLimit(int limit) {
    this.limit = limit;

  public void insertString(int offset, String str, AttributeSet attr)
      throws BadLocationException {
    if (str == null)

    if ((getLength() + str.length()) <= limit) {
      super.insertString(offset, str, attr);

public class Main {
  public static void main(String[] argv) {

    JTextField textfield1 = new JTextField(15);
    textfield1.setDocument(new JTextFieldLimit(10));

15.12.1.Custom Document FilterCustom Document Filter
15.12.2.extends PlainDocument to create a float value type text field
15.12.3.extends PlainDocument to create alpha and numeric value based field field
15.12.4.Element WalkerElement Walker
15.12.5.Implement a document cleaner that maps lowercase letters to uppercase
15.12.6.Limit JTextField input to a maximum length