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

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 17:29   1320   0

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;

}

}

}*/

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP