Limiting the Capacity of a JTextComponent using custom DocumentFilter - Java Swing

Java examples for Swing:JTextComponent

Description

Limiting the Capacity of a JTextComponent using custom DocumentFilter

Demo Code


import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.JTextComponent;

public class Main {
  public static void main(String[] args) throws Exception {
    JTextComponent textComponent = new JTextField();
    AbstractDocument doc = (AbstractDocument) textComponent.getDocument();
    doc.setDocumentFilter(new FixedSizeFilter(10));

  }//from   www.  j av a 2 s  .c o  m
}

class FixedSizeFilter extends DocumentFilter {
  int maxSize;

  public FixedSizeFilter(int limit) {
    maxSize = limit;
  }
  public void insertString(DocumentFilter.FilterBypass fb, int offset,
      String str, AttributeSet attr) throws BadLocationException {
    replace(fb, offset, 0, str, attr);
  }

  public void replace(DocumentFilter.FilterBypass fb, int offset, int length,
      String str, AttributeSet attrs) throws BadLocationException {
    int newLength = fb.getDocument().getLength() - length + str.length();
    if (newLength <= maxSize) {
      fb.replace(offset, length, str, attrs);
    } else {
      throw new BadLocationException(
          "New characters exceeds max size of document", offset);
    }
  }
}

Related Tutorials