我该如何使用代码?我知道我可以使用JFormattedTextField,但是我正在创建自己的库,以便JTextField也可以这样做。这是我尝试过的方法:


OnKeyRelease:是的,这是我找到的最好的方法,我将所有想要的字符替换为“”。但这有点慢,我的意思是当键按下时它仍然显示禁止的字符,并在键释放时删除它,就像它的事件名称一样。这困扰着我。
evt.consume:我不知道为什么这种方法除了数字和字母之外还可以用于其他任何东西,例如Backspace,Home等。是否知道如何使这种方法也可以用于数字或字母?


如果您能给我一个提示或链接,我将不胜感激,谢谢:)

最佳答案

如果您能给我一个提示或链接,我将不胜感激,谢谢:)


Text Component Features - Implementing a Document Filter怎么样?


要实现文档过滤器,请创建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());

关于java - 防止JTextField中的字母数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16987604/

10-11 22:28
查看更多