Custom Document Filter : Document « Swing Event « Java Tutorial

Custom Document Filter
import javax.swing.JFrame;
import javax.swing.JTextField;
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;

class IntegerRangeDocumentFilter extends DocumentFilter {

  public IntegerRangeDocumentFilter() {


  public void insertString(DocumentFilter.FilterBypass fb, int offset, String string,
      AttributeSet attr) throws BadLocationException {
    System.out.println("insert string"+ string);
    super.insertString(fb, offset, string, attr);

  public void remove(DocumentFilter.FilterBypass fb, int offset, int length)
      throws BadLocationException {

    super.remove(fb, offset, length);

  public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text,
      AttributeSet attrs) throws BadLocationException {
    super.replace(fb, offset, length, text, attrs);

public class RangeSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Range Example");

    JTextField textFieldOne = new JTextField();
    Document textDocOne = textFieldOne.getDocument();
    DocumentFilter filterOne = new IntegerRangeDocumentFilter();
    ((AbstractDocument) textDocOne).setDocumentFilter(filterOne);

    frame.setSize(250, 150);

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