jTextField如何限制输入字符长度?

cheliver 2005-10-22 08:30:21
JTextField jTextField1 = new JTextField(5);
为什么还是可以输入5个以上的字符?我输入的是英文字符,应该如何限制,谢拉
...全文
411 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
紫炎圣骑 2005-10-22
  • 打赏
  • 举报
回复
JTextComponent textComp = new JTextField();
textComp.setDocument(new FixedSizePlainDocument(10));

class FixedSizePlainDocument extends PlainDocument {
int maxSize;

public FixedSizePlainDocument(int limit) {
maxSize = limit;
}

public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if ((getLength() + str.length()) <= maxSize) {
super.insertString(offs, str, a);
} else {
throw new BadLocationException("Insertion exceeds max size of document", offs);
}
}
}
congliu 2005-10-22
  • 打赏
  • 举报
回复
监听onKeyPressed事件,
if (jtext.Length()>4){//如果输入的字符数大于4

楼主要处理的代码

}

62,626

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧