如果您能给我一个线索或链接,我将不胜感激,谢谢:)
文本组件功能如何- 实现文档过滤器?
要实现文档过滤器,请创建一个子类,DocumentFilter
然后使用该类setDocumentFilter
中定义的方法将其附加到文档中AbstractDocument
。
这可能会有所帮助:
public class NoAlphaNumFilter extends DocumentFilter {
String notAllowed = "[A-Za-z0-9]";
Pattern notAllowedPattern = Pattern.compile(notAllowed);
public void replace(FilterBypass fb, int offs,
int length,
String str, AttributeSet a)
throws BadLocationException {
super.replace(fb, offs, len, "", a); // clear the deleted portion
char[] chars = str.toCharArray();
for (char c : chars) {
if (notAllowedPattern.matcher(Character.toString(c)).matches()) {
// not allowed; advance counter
offs++;
} else {
// allowed
super.replace(fb, offs++, 0, Character.toString(c), a);
}
}
}
}
将此应用于JTextField
:
((AbstractDocument) myTextField.getDocument()).setDocumentFilter(
new NoAlphaNumFilter());