我试图限制用户可以在文本字段中输入的字符的最大长度,但它似乎不起作用。
这是代码:
text2 = new JTextField("Enter text here",8);
我做错了什么吗?如何才能使限制正常工作?
您当前的代码没有设置最大长度,而是定义可见列的数量。
要限制数据的最大长度,您可以设置自定义Document http://docs.oracle.com/javase/7/docs/api/javax/swing/text/Document.html对于不允许添加超出最大长度限制的文本字段:
public final class LengthRestrictedDocument extends PlainDocument {
private final int limit;
public LengthRestrictedDocument(int limit) {
this.limit = limit;
}
@Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if (str == null)
return;
if ((getLength() + str.length()) <= limit) {
super.insertString(offs, str, a);
}
}
}
然后设置您的文本字段以使用此文档:
text2.setDocument(new LengthRestrictedDocument(8));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)