limiteddocument.java
来自「输入框的字符与长度限制.调用方法源码里有说明.主要是覆盖setDocument方」· Java 代码 · 共 57 行
JAVA
57 行
//文件名:LimitedDocument.java
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class LimitedDocument extends PlainDocument {
private int maxLength = -1;
private String allowCharAsString = null;
public LimitedDocument() {
super();
}
public LimitedDocument(int maxLength, String str) {
super();
this.maxLength = maxLength;
allowCharAsString = str;
}
@Override
public void insertString(int offset, String str, AttributeSet attrSet)
throws BadLocationException {
if (str == null) {
return;
}
if (allowCharAsString != null && str.length() == 1) {
if (allowCharAsString.indexOf(str) == -1) {
return;
}
}
char[] charVal = str.toCharArray();
String strOldValue = getText(0, getLength());
byte[] tmp = strOldValue.getBytes();
if (maxLength != -1 && (tmp.length + charVal.length > maxLength)) {
return;
}
super.insertString(offset, str, attrSet);
}
}
// 用法:
// LimitedDocument Input = new LimitedDocument(maxLength,allowCharAsString); maxLength 为最大输入长度,allowCharAsString 为允许输入的字符
// jTextField.setDocument(Input); 运用到文本框中
// 例如:
// String AllowChar = "0123456789";
// LimitedDocument Input = new LimitedDocument(11,AllowChar);
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?