Created
January 14, 2022 03:34
-
-
Save RustyKnight/3318d35484e90474373cd4b32c4dd72c to your computer and use it in GitHub Desktop.
A document filter which can support a regular expression
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 java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
import javax.swing.text.AttributeSet; | |
import javax.swing.text.BadLocationException; | |
import javax.swing.text.DocumentFilter; | |
public class RegularExpressionDocumentFilter extends ChainedDocumentFilter { | |
// Useful for every kind of input validation ! | |
// this is the insert pattern | |
// The pattern must contain all subpatterns so we can enter characters into a text component ! | |
private Pattern pattern; | |
public RegularExpressionDocumentFilter(DocumentFilter filter, Pattern pattern) { | |
super(filter); | |
this.pattern = pattern; | |
} | |
public RegularExpressionDocumentFilter(Pattern p) { | |
this(null, p); | |
} | |
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { | |
String newStr = fb.getDocument().getText(0, fb.getDocument().getLength()) + string; | |
Matcher m = pattern.matcher(newStr); | |
if (m.matches()) { | |
super.insertString(fb, offset, string, attr); | |
} else { | |
} | |
} | |
public void replace(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