public class LengthLimitedTextField extends JTextField { private static int cols; public LengthLimitedTextField(int cols) { super(cols); this.cols = cols; }
protected Document createDefaultModel() { return new LengthLimitedDocument(); }
static class LengthLimitedDocument extends PlainDocument { public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { if (str == null) { return; } if ((getLength() + str.length()) <= cols) { char[] upper = str.toCharArray(); int length = 0; for (int i = 0; i < upper.length; i++) { upper[length++] = Character.toUpperCase(upper[i]); } System.out.println(str); super.insertString(offs, new String(upper, 0, length), a); } } } }
要么设长度jTextField1.setBounds(180, 20, 长度, 20);
jtf.setSize(20, 30);//jtf显示的宽度和长度
如果是要设置在输入10字符之后就不能再输入,则:必须增加DocumentListener.用自定义的方法,获得length如果length==10之后就不再改变了!
private static int cols;
public LengthLimitedTextField(int cols) {
super(cols);
this.cols = cols;
}
protected Document createDefaultModel() {
return new LengthLimitedDocument();
}
static class LengthLimitedDocument extends PlainDocument { public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException { if (str == null) {
return;
} if ((getLength() + str.length()) <= cols) { char[] upper = str.toCharArray();
int length = 0;
for (int i = 0; i < upper.length; i++) {
upper[length++] = Character.toUpperCase(upper[i]);
}
System.out.println(str);
super.insertString(offs, new String(upper, 0, length), a);
}
}
}
}