Search code examples
javaswingjtextfieldjformattedtextfield

Prevent alphanumerics in JTextField


How do I do this with code? I know I can use a JFormattedTextField, but I'm making my own library so that JTextFields can also do this. Here are the methods I've tried:

  1. OnKeyRelease: Yes, this is the best method I've found, I replaced all the chars I want with "". But it kinda slow, I mean it still shows the forbidden chars when the key is down, and remove the chars when the key released, just like its event name. Which bothers me.
  2. evt.consume: I don't know why this method works for anything except numbers and letters, such as Backspace, Home, etc. Any idea how to make this method also work on numbers or letters?

If you could give me a clue or link I would be grateful, thanks :)


Solution

  • If you could give me a clue or link I would be grateful, thanks :)

    How about Text Component Features - Implementing a Document Filter?

    To implement a document filter, create a subclass of DocumentFilter and then attach it to a document using the setDocumentFilter method defined in the AbstractDocument class.

    This might help:

    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);
                }
            }
        }
    }
    

    To apply this to a JTextField:

    ((AbstractDocument) myTextField.getDocument()).setDocumentFilter(
      new NoAlphaNumFilter());