Setting maximum number of characters in JTextField
1
Sep/090
Sep/090
The default implementation of JTextField not allow set maximum number of characters. To enable this resource you need implements a Document, overriding insertString method.
public class MaxLengthTextDocument extends PlainDocument {
//Store maximum characters permitted
private int maxChars;
@Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if(str == null || (getLength() + str.length() > maxChars)){
str = str.substring(0, maxChars);
}
super.insertString(offs, str, a);
}
//getter e setter omitted
}
Here we defined one class called MaxLengthTextDocument that extends PlainDocument. In insertString attribute, we checked if quantity of characters greater than maxChars attribute, cutting String if true.
After this, only insert our implementation in JTextField, this way:
... MaxLengthTextDocument maxLength = new MaxLengthTextDocument(); maxLength.setMaxChars(50);//50 is a maximum number of character jTextField.setDocument(maxLength); ...
And voilà!
See ya!
Comments (0)
Trackbacks (0) ( subscribe to comments on this post )
No comments yet.
Leave a comment
No trackbacks yet.
Português