Limiting the length of text entered in a JTextField

Create a custom component that extends from JTextField and allow the user to specify a maximum length. The implementation is simple: capture the insertString method and execute super.insertString when the condition (current length < = maximumlength) is met.

Main.java:

import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      getContentPane().add(new LimitedTextField("Try typing more", 15, 15));
      getContentPane().add(new LimitedTextField(10, 3));
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(300, 300);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}
 
class LimitedTextField extends JTextField
{
   private int maxCols = 0;
 
   public LimitedTextField(int maxCols) {
      super();
      this.maxCols = maxCols;
   }
 
   public LimitedTextField(int cols, int maxCols) {
      super(cols);
      this.maxCols = maxCols;
   }
  
   public LimitedTextField(String text, int maxCols) {
      super();
      this.maxCols = maxCols;
      setText(text);
   } 
 
   public LimitedTextField(String text, int cols, int maxCols) {
      super(cols);
      this.maxCols = maxCols;
      setText(text);
   }
 
   protected Document createDefaultModel() {
      return new LimitedDocument();
   }
  
   protected class LimitedDocument extends PlainDocument {
      public void insertString(int offset, String str, AttributeSet as) 
            throws BadLocationException  {
         if (str == null || getLength() + str.length() <= maxCols) {
            super.insertString(offset, str, as);
         }
         else {
            int remainder = maxCols – getLength();
            if (remainder > 0) {
               super.insertString(offset, str.substring(0, remainder), as);
            }
         }
      }
   }
}