Created
January 14, 2022 03:33
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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