/**
* 文本框仅能输入数字 用法:JTextField.setDocument(new NumOnlyDocument());
*
*
*/
class NumOnlyDocument extends PlainDocument {
private static final long serialVersionUID = 1L;
public void insertString(int offset, String s, AttributeSet attrSet)
throws BadLocationException {
try {
Integer.parseInt(s);
} catch (NumberFormatException ex) {
return;
}
super.insertString(offset, s, attrSet);
}
}使用Integer.parseInt(s)无法将全角数字剔除
可使用以下代码替换
Pattern pt = Pattern. compile( "^\\d*");
if (!pt.matcher(s).matches())
return ;
本文探讨了在编程中如何通过正则表达式限制文本框仅能输入数字,详细介绍了`Pattern`类与`Matcher`方法的使用,以及如何在遇到非数字字符时进行有效拦截。
1923

被折叠的 条评论
为什么被折叠?



