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.
Ok, I finally get how it works! I needed to use if
s in replace()
method, because that's the code that gets called everytime the user inputs/pastes anything in the JTextField
:
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;
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);
}
}