Someone knows why in a JtextField, when I set the setDocument() property -class PlainDocument- when I execute the program, it shows me the field ok, but only I can enter N-1 characters, when I set the maxlength prop to N characters length.
// Block 1
txtPais.setDocument(new MaxLengthTextCntry());
I have another class which internally set the maximum length
// Block 2
public class MaxLengthTextCntry extends MaxLengthGeneric{
public MaxLengthTextCntry(
{
super(2);
}
}
Finally the MaxLengthGeneric class
// Block 3
public abstract class MaxLengthGeneric extends PlainDocument {
private int maxChars;
public MaxLengthGeneric(int limit) {
super();
this.maxChars = limit;
}
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if (str != null && (getLength() + str.length() < maxChars)) {
super.insertString(offs, str, a);
}
}
}
SOLUTION
Maintaining Block 2, I replaced block 1 with
((AbstractDocument) txtRucnumero.getDocument()).setDocumentFilter(new MaxLengthTextRuc());
Block 3 changed dependence from DocumentFilter. Don't forget to implement both parent methods insertString() and replace()!!
public abstract class MaxLengthGeneric extends DocumentFilter {
...
@Override
public void insertString(FilterBypass fb, int offs, String str,
AttributeSet a) throws BadLocationException {
if ((fb.getDocument().getLength() + str.length()) <= maxChars)
super.insertString(fb, offs, str, a);
else
Toolkit.getDefaultToolkit().beep();
}
@Override
public void replace(FilterBypass fb, int offs, int length, String str,
AttributeSet a) throws BadLocationException {
if ((fb.getDocument().getLength() + str.length() - length) <= maxChars)
super.replace(fb, offs, length, str, a);
else
Toolkit.getDefaultToolkit().beep();
}
}
OR SOLUTION 2 (Or maybe The importance of debugging for Jnewbies life: < replace with <=)
** if (str != null && (getLength() + str.length() <= maxChars)) {**
MaxLengthTextArea is a class extended from PlainDocument: used just to set via parameter the number of characters I want for that field
As I suggested in my comment you should be using a DocumentFilter
. Read the section from the Swing tutorial on Implementing a Document Filter for more information and a working example.