Java Swing How to - Limit the amount of characters in JTextPane as the user types








Question

We would like to know how to limit the amount of characters in JTextPane as the user types.

Answer

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
//from  w  w w .jav a  2  s.  c o  m
public class Main extends JFrame {
  private JPanel panel = new JPanel();
  private JTextPane tpane = new JTextPane();
  private AbstractDocument abDoc;

  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Document doc = tpane.getStyledDocument();
    if (doc instanceof AbstractDocument) {
      abDoc = (AbstractDocument) doc;
      abDoc.setDocumentFilter(new DocumentSizeFilter(3));
    }
    panel.add(tpane);
    add(panel);
    pack();
  }
  public static void main(String... args) {
    new Main().setVisible(true);
  }
}

class DocumentSizeFilter extends DocumentFilter {
  int len;
  public DocumentSizeFilter(int max_Chars) {
    len = max_Chars;
  }
  public void insertString(FilterBypass fb, int offset, String str,
      AttributeSet a) throws BadLocationException {
    System.out.println("In DocumentSizeFilter's insertString method");
    if ((fb.getDocument().getLength() + str.length()) <= len){
      super.insertString(fb, offset, str, a);
    }
  }
  public void replace(FilterBypass fb, int offset, int length, String str,
      AttributeSet a) throws BadLocationException {
    System.out.println("In DocumentSizeFilter's replace method");
    if ((fb.getDocument().getLength() + str.length() - length) <= len){
      super.replace(fb, offset, length, str, a);
    }
  }
}