Skip to content

Instantly share code, notes, and snippets.

@RustyKnight
Created January 14, 2022 03:33
Show Gist options
  • Save RustyKnight/d036c5813ced7c5204ca25e25a2cdb05 to your computer and use it in GitHub Desktop.
Save RustyKnight/d036c5813ced7c5204ca25e25a2cdb05 to your computer and use it in GitHub Desktop.
Document filter that limits the length of the input to a set number of characters
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class LengthLimitDocumentFilter extends ChainedDocumentFilter {
private int maxCharacters;
public LengthLimitDocumentFilter(DocumentFilter filter, int maxChars) {
super(filter);
maxCharacters = maxChars;
}
public LengthLimitDocumentFilter(int maxChars) {
maxCharacters = maxChars;
}
public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException {
if ((fb.getDocument().getLength() + str.length()) <= maxCharacters) {
super.insertString(fb, offs, str, a);
} else {
provideErrorFeedback();
}
}
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException {
if ((fb.getDocument().getLength() + str.length() - length) <= maxCharacters) {
super.replace(fb, offs, length, str, a);
} else {
provideErrorFeedback();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment