How To limit the number of characters in JTextField?

Viewed 117384

How to limit the number of characters entered in a JTextField?

Suppose I want to enter say 5 characters max. After that no characters can be entered into it.

8 Answers

Just put this code in KeyTyped event:

    if ((jtextField.getText() + evt.getKeyChar()).length() > 20) {
        evt.consume();
    }

Where "20" is the maximum number of characters that you want.

Related