How to Limit the Number of Characters in a JTextField of Java
A JTextField is a component in the standard Java GUI system with which a user can input a string of words into a form. As an interface component, most of JTextField's methods involve handling input from the user, while the actual contents of the field are handled by the JTextField's associated Document. To limit a user's input, simply prevent the document from changing if the length of the input string exceeds the maximum length you specify.
Instructions
-
-
1
Create a new subclass of PlainDocument, e.g. "class LimitedDocument extends PlainDocument." This class needs one field, an integer called "textLimit" that will store the maximum allowable length.
-
2
Create new constructors that accept a "limit" parameter. In the body of the constructor, call the super-class's constructor via "super();" and set the textLimit field to the value of the limit parameter.
-
-
3
Override the insertString method inherited from PlainDocument, which takes an integer, String and AttributeSet as parameters. In the body of the method, check to see if the document's current length, accessed via getLength(), plus the length of the string to insert is less than the value of textLimit. If so, call the inherited insertString(int, String, AttributeSet).
-
4
Create and add an instance of the new document type to your JTextField, e.g. "textField.setDocument(new LimitedDocument(x));", where "x" is the maximum allowable number of characters.
-
1
Tips & Warnings
Add a JLabel somewhere next to this modified JTextField with the number you chose for textLimit to signal to the user that their input will be restricted.
References
- Photo Credit Jupiterimages/Pixland/Getty Images