javaswingvalidationjtextfielddocumentlistener

Smarter way to use Java DocumentListener


Currently I am using the DocumentListener on every textfield, to live validate the users input, but I am thinking there must be a smarter way, since I am repeating my self so much.

Is there a smarter way of doing it?

nameJTextField.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void insertUpdate(DocumentEvent e) {
            validateName(nameJTextField.getText());
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            validateName(nameJTextField.getText());
        }

        @Override
        public void changedUpdate(DocumentEvent e) {

        }

        private void validateName(String name) {
             if (name.matches("^[A-ZÆØÅa-zæøå0-9]{2,40}$")) {
                 errorNameJLabel.setText("");
             } else {
                 errorNameJLabel.setText("Min 2 and max 40 letters and numbers");
             }
        }
    });

Solution

  • Not in the built-in java. I do a lot with DocumentListeners and want to do exactly this, so I made my own class:

    https://github.com/MattPutnam/Common/blob/master/src/common/swing/DocumentAdapter.java

    Feel free to copy/paste.