我需要限制JTextField中的字符数量。我使用了以下代码来实现,但问题是我使用虚拟键盘向JTextField提供数据。因此,偏移量始终设置为0。当我输入超过指定数量的字符时,它会重置字段并重新开始。例如,如果我的限制是3个字符,并且我输入
xyz0
,那么我的受限制的文本框将读取字符直到z
,然后清除字段并重新开始。因此,我在字段中只剩下0
。代码如下。 public class JTextFieldLimit extends PlainDocument {
private int limit;
public JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
@Override
public void insertString( int offset, String str, AttributeSet attr ) throws BadLocationException {
if (str == null) return;
System.out.println("from document helper getLength():"+getLength());
System.out.println("from document helper str.length():"+str.length());
System.out.println("from document helper str:"+str);
System.out.println("from document helper attr:"+attr);
System.out.println("from document helper offset:"+offset);
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}