javaswingdocumentfilter

What do each of the methods (and arguments of) of DocumentFilter do exactly?


I've been struggling to wrap my head around this DocumentFilter business, and just when I feel like I understood it mostly, I tried out a simple test case that just didn't make any sense.

So the goal initially was to create a simple DocumentFilter to allow numbers only, including decimals. I did some research and read up on the few posts already existing here on StackOverflow that detail the process very well. Thank you to those who posted in those. I also read up on Regex for the first time and had my mind blown by how versatile it is.

Moving on, I wrote (mostly copied) one of the examples and tried it out on my program, but for some reason it just wasn't working. I decided to go back to basics and try out a very very simple subclass of DocumentFilter:

public class SomeFilter extends DocumentFilter {

    public void insertString(FilterBypass fb, int offs, String str,
        AttributeSet a) throws BadLocationException {

        if (str.matches("B")) super.insertString(fb, offs, str, a);
    }

    public void replace(FilterBypass fb, int offs, int len, String str,
        AttributeSet a) throws BadLocationException {

        if (str.matches("A")) super.replace(fb, offs, len, str, a);
    }
}

This is what is really throwing me off now. From the oracle documents, I read that insertString is to insert stuff (I'm assuming where the cursor is) and replace is to replace (such as for Copy and Paste). Now clearly I'm misunderstanding something here because the JTextField that I use setDocumentFilter on only lets me "insert" A's and not B's. Can someone please explain how these methods actually work?

If I can get this figured out I will later post what I had for the actual IntegerFilter to see if I can get that worked out as well.


Solution

  • When you type text into a JTextComponent, the replace(...) method of the DocumentFilter will be invoked. This is because the replaceSelection(...) method of the JTextComponent ends up being invoked by the text insert action.

    If you insert text directly into the Document using the insertString(...) method of the Document, then the insertString(...) method of the DocumentFilter will be invoked.