有人知道为什么在 JtextField 中,当我设置 setDocument() 属性 -class PlainDocument- 时,当我执行程序时,它显示该字段正常,但是当我将 maxlength 属性设置为 N 时,只有我可以输入 N-1 个字符字符长度。
// Block 1
txtPais.setDocument(new MaxLengthTextCntry());
我有另一个在内部设置最大长度的类
// Block 2
public class MaxLengthTextCntry extends MaxLengthGeneric{
public MaxLengthTextCntry(
{
super(2);
}
}
最后是MaxLengthGeneric类
// 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);
}
}
}
解决方案
维护第 2 块,我将第 1 块替换为
((AbstractDocument) txtRucnumero.getDocument()).setDocumentFilter(new MaxLengthTextRuc());
块 3 更改了对 DocumentFilter 的依赖。不要忘记实现两个父方法 insertString() 和 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();
}
}
或解决方案2(或者也许调试对Jnewbies生活的重要性:<替换为<=)
** if (str != null && (getLength() + str.length() <= maxChars)) {**