限定文本框输入长度和类型

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/*
限定文本框允许输入的字符串长度类
*/
@SuppressWarnings("serial")
public class LimitTextLength extends PlainDocument {

int maxLength;

// 有参构造,参数为文本框输入字符最大长度
public LimitTextLength(int newMaxLength) {
super();
maxLength = newMaxLength;
}

/*
* 重载父类方法
*/
public void insertString(int offset,String str, AttributeSet a) throws BadLocationException{
if (getLength() + str.length() > maxLength) {
return;
} else {
super.insertString(offset, str, a);
}
}

}

/*限制输入的所有字符皆为数字,如果不是数字则发出声音
class maxLengthDocument extends PlainDocument {
//设置文档的最大显示字符数目
int maxChars;
public maxLengthDocument(int max) {
maxChars = max;
}

public void insertString(int offset, String s, AttributeSet a) throws
BadLocationException {

if (s.matches("[0-9]")) {
super.insertString(offset, s, a);
} else {
Toolkit.getDefaultToolkit().beep();
return;
}
}
}*/

原文地址:https://www.cnblogs.com/zhuimingzhenbai/p/13074303.html