Skip to content

Instantly share code, notes, and snippets.

@RustyKnight
Created January 14, 2022 03:31
Show Gist options
  • Save RustyKnight/006af7bbbb7213de79d6d0b9c9069187 to your computer and use it in GitHub Desktop.
Save RustyKnight/006af7bbbb7213de79d6d0b9c9069187 to your computer and use it in GitHub Desktop.
A document filter which restricts input to characters only (alphabetical)
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class CharacterOnlyDocumentFilter extends ChainedDocumentFilter {
public CharacterOnlyDocumentFilter(DocumentFilter filter) {
super(filter);
}
@Override
public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
StringBuilder buffer = new StringBuilder(string);
for (int i = buffer.length() - 1; i >= 0; i--) {
char ch = buffer.charAt(i);
if (!Character.isAlphabetic(ch)) {
buffer.deleteCharAt(i);
}
}
super.insertString(fb, offset, buffer.toString(), attr);
}
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String string, AttributeSet attr) throws BadLocationException {
if (length > 0) {
fb.remove(offset, length);
}
insertString(fb, offset, string, attr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment