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)){
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 minor than maxChars attribute, inserting in 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 on 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 on 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!
August 13th, 2010 on 20:10
Thank you , Good Job
but i have a note that
if((getLength() + str.length() <= maxChars))
{
super.insertString(offs, str, a);
}
this condition is enough and i try it
thanks
August 31st, 2010 on 00:05
Thanks for your best turotial.
But I suggest you must use “str = null;” instead of “str = str.substring(0, maxChars);”. Because a run time error occurs when we use more than maxChars.
September 3rd, 2010 on 16:20
Thanks. This was fixed! But I changed the “IF” clause to insert the String part only if total length does not exceed the allowed length.