Created
January 14, 2022 03:31
-
-
Save RustyKnight/006af7bbbb7213de79d6d0b9c9069187 to your computer and use it in GitHub Desktop.
A document filter which restricts input to characters only (alphabetical)
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 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