如何限制 JTextField 的字符数
我必须限制 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);
}
}
}
I have to restrict the number of characters in the JTextField. I used the following code to do that but the problem is i am feeding the data to JTextField using the virtual keyboard. So the offset is set to 0 all the time. When i enter more than the specified number of characters it resets the field and start doing it from the beginning. For example if my limit is 3 characters and i am entering xyz0
my limited textbox reads the character upto z
and then clears the field and restart again. So i am left with 0
in the field. The code is as follows.
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);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该按照本教程使用 DocumentFilter。例如:
You should use a DocumentFilter as per this tutorial. For example: