1 import javax.swing.text.AttributeSet;
2 import javax.swing.text.BadLocationException;
3 import javax.swing.text.PlainDocument;
4
5 public class LimitedDocument extends PlainDocument {
6
7 private int maxLength = -1;
8 private String allowCharAsString = null;
9
10 public LimitedDocument() {
11 super();
12 }
13
14 public LimitedDocument(int maxLength, String str) {
15 super();
16 this.maxLength = maxLength;
17 allowCharAsString = str;
18 }
19
20 @Override
21 public void insertString(int offset, String str, AttributeSet attrSet)
22 throws BadLocationException {
23
24 if (str == null) {
25 return;
26 }
27
28 if (allowCharAsString != null && str.length() == 1) {
29 if (allowCharAsString.indexOf(str) == -1) {
30 return;
31 }
32 }
33
34 char[] charVal = str.toCharArray();
35 String strOldValue = getText(0, getLength());
36 byte[] tmp = strOldValue.getBytes();
37
38 if (maxLength != -1 && (tmp.length + charVal.length > maxLength)) {
39 return;
40 }
41
42 super.insertString(offset, str, attrSet);
43 }
44 }
用法:
1 LimitedDocument Input = new LimitedDocument(maxLength,allowCharAsString);
2 maxLength 为最大输入长度,allowCharAsString 为允许输入的字符
3 jTextField.setDocument(Input); 运用到文本框中
例如:
1 String AllowChar = "0123456789";
2 LimitedDocument Input = new LimitedDocument(11,AllowChar)