可以继承PlainDocument, 重写insertString( String, int, AttributeSet )方法, 在该方法里进行判断, 然后通过JTextField的setDocument( Document ).class YourDocument extends PlainDocument
{
public void insertString( String str, int length, AttributeSet set )
{
}
}
{
public void insertString( String str, int length, AttributeSet set )
{
}
}
if (!(s == null)) {
String str = super.getText(0,super.getLength());
if(str.length>=(intMaxLength)
return;
}
}public void setMaxLength(int MaxLength){
intMaxLength = MaxLength;
}
}YourDocument doc = new YourDocument();
JTextField jText = new JTextField();
doc.setMaxLength(4);
jText.setDocment(doc);
if (!(s == null)) {
String str = super.getText(0,super.getLength());
if(str.length>=(intMaxLength)
return;
}
super.insertString(offset,s,attributeSet);
}
String str = super.getText(0,super.getLength());
str的长度是1,但是s的长度是3
这样子,你照样会把s插入.等下次判断的时候不能输入了.当然,用键盘输入不可能一次输入两个以上的字符,所以,各位的判断看起来没有问题,但是,想想如果是用copy过来的一段字符,应该怎么办.下面是我的建议:
1.新建一个class MyDocument,继承PlainDocument
2.重载insertString()方法,代码如下
public void insertString(int offset, String s, AttributeSet attributeSet) throws BadLocationException){
if (!(s == null)) {
String strOld = getText(0,getLength());
if(strOld.length()+s.length()>3 //注意这里的判断条件
return;
}
super.insertString(offset,s,attributeSet);
}3.textField.setDocument(new MyDocument());