1Sep/092
Setting maximum number of characters in JTextField
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!
July 8th, 2010 - 07:53
str==null why str=str.subString(0…..
I try it but wrong…
if (getLength() + str.length() > limit) {
str = str.substring(0, limit – getLength());
it’s worked
and create setMaxChars(int MaxChars) metod ofcourse
July 8th, 2010 - 10:24
Sorry, my mistake.
The correct operator is “!=”, not “==”. You should to use “str != null” because if str is null “str.length()” will throw NullPointerException.
Thanks for notice!