您的位置:首页 > 编程语言

JTextField设置最大长度的小代码

2009-02-20 11:49 253 查看
textfield.setDocument(new PlainDocument() {
int MAX_LENGTH = 20;
public void insertString(int offset, String s,
AttributeSet attributeSet) throws BadLocationException {
if (s == null || offset < 0) {
return;
}
for (int i = 0; i < s.length(); i++) {
if (getLength() > MAX_LENGTH - 1) {
break;
}
super.insertString(offset + i, s.substring(i, i + 1),
attributeSet);
}
return;
}
});


直接插入这段代码就可以了,直接替换掉textfield的Document。默认最大长度是20,想改成什么样自己调吧。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: