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);
    System.out.println(offset);
    super.insertString(fb, offset, string, attr);
  }

  public void remove(DocumentFilter.FilterBypass fb, int offset, int length)
      throws BadLocationException {
    System.out.println("remove");

    
    super.remove(fb, offset, length);
  }

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

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

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

    frame.setSize(250, 150);
    frame.setVisible(true);
  }
}










15.12.Document
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