您需要利用 Documents DocumentFilter
public class SizeFilter extends DocumentFilter {
private int maxCharacters;
public SizeFilter(int maxChars) {
maxCharacters = maxChars;
}
public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
throws BadLocationException {
if ((fb.getDocument().getLength() + str.length()) > maxCharacters)
int trim = maxCharacters - (fb.getDocument().getLength() + str.length()); //trim only those characters we need to
fb.remove(0, trim);
}
super.insertString(fb, offs, str, a);
}
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a)
throws BadLocationException {
if ((fb.getDocument().getLength() + str.length() - length) > maxCharacters) {
int trim = maxCharacters - (fb.getDocument().getLength() + str.length() - length); // trim only those characters we need to
fb.remove(0, trim);
}
super.replace(fb, offs, length, str, a);
}
}
基于来自http://www.jroller.com/dpmihai/entry/documentfilter的字符限制过滤器
您需要将其应用于文本区域 Text 组件,因此...
((AbstractDocument)field.getDocument()).setDocumentFilter(...)