javaswingjtextfielddocumentfilter

Java - Use a DocumentFilter to limit allowed characters and length


Is it possible to use a single DocumentFilter to limit both the allowed characters and the number of characters in a JTextField? I don't get how to do both and I didn't find any fully working workaround.


Solution

  • Ok, I finally get how it works! I needed to use ifs in replace() method, because that's the code that gets called everytime the user inputs/pastes anything in the JTextField:

    1. if the already inserted text length (fb.getDocument().getLength()) summed to the user current input/paste (text.length()) is greater than the intended limit (I setted it to 12 characters), first delete any invalid characters from the user input (text.replaceAll(regex, "")) and then truncate it so that it does not exceed the limit;
    2. otherwise, if the text would not exceed the limit, just delete any possible invalid characters.

     

    class NameFilter extends DocumentFilter {
        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            int finalLength = fb.getDocument().getLength() + text.length();
    
            if(finalLength > 12) {
                fb.replace(offset, length, text.replaceAll("[^a-zA-Z0-9/&\\-':;.,?!@]", "").substring(0, 12-fb.getDocument().getLength()), attrs);
                Toolkit.getDefaultToolkit().beep();
            } else
                fb.replace(offset, length, text.replaceAll("[^a-zA-Z0-9/&\\-':;.,?!@]", ""), attrs);
        }
    }