我正在尝试创建Java IMEI校验和计算器。 校验和是IMEI 15位数的最后一位数。
因此,我需要创建限制为14个字符的JTextField,并且仅限于数字!
对于14个字符的限制,我创建了一个类,将PlainDocument扩展如下:
public final class LengthRestrictedDocument extends PlainDocument {
private final int limit;
public LengthRestrictedDocument(int limit) {
this.limit = limit;
}
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if (str == null)
return;
if ((getLength() + str.length()) <= limit) {
super.insertString(offs, str, a);
}
}
}
然后我将它应用到JTextField,如下所示:
PlainDocument document = new LengthRestrictedDocument(14);
tfImei.setDocument(document); //Restricting inputs to 14 digits
仅对于数字,我试图像这样使用DocumentFilter:
DocumentFilter docFilter = new DocumentFilter() {
Pattern regEx = Pattern.compile("\\d+");
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
Matcher matcher = regEx.matcher(text);
if (!matcher.matches()) {
return;
}
super.replace(fb, offset, length, text, attrs);
}
};
我使用它如下:
PlainDocument document = new LengthRestrictedDocument(14);
document.setDocumentFilter(docFilter);
tfImei.setDocument(document); //Restricting inputs to 14 digits
它只为数字工作但它取消了14位数限制。
有人可以帮助实现这样的功能吗? 仅限14个字符和数字?
答案 0 :(得分:2)
对于14个字符的限制,我创建了一个类,将PlainDocument扩展如下:
这是一种较旧的方法。较新的方法是使用DocumentFilter。请查看Implementing a DocumentFilter上Swing教程中的部分以获取工作示例。
仅对于数字,我试图像这样使用DocumentFilter。它只为数字工作但它取消了14位数限制。
请勿使用自定义文档和DocumentFilter。
相反,您可以将功能组合到一个DocumentFilter中。
或者对于更简单的解决方案,您可以使用JFormattedTextField
。您可以指定一个控制数字位数和每个数字类型的掩码:
MaskFormatter format = new MaskFormatter( "##############" );
JFormattedTextField ftf = new JFormattedTextField( mf );
本教程有一个关于How to Use Text Fields
的部分,以获取更多信息和示例。
对于更灵活的方法,您可能需要查看Chaining Document Filters。它允许您将多个DocumentFilter组合到一个过滤器中,因此如果任何编辑失败,则会阻止插入。这允许您创建可在不同情况下使用的可重用过滤器。
答案 1 :(得分:0)
最后,我有这个工作! 是的,我使用过文档过滤器如下:
DocumentFilter docFilter = new DocumentFilter() {
Pattern regEx = Pattern.compile("\\d+");
final int maxCharLength = 14;
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
Matcher matcher = regEx.matcher(text);
if ((fb.getDocument().getLength() + text.length()) <= maxCharLength && matcher.matches()) {
super.replace(fb, offset, length, text, attrs);
}else{
Toolkit.getDefaultToolkit().beep();
}
}
};
AbstractDocument absDoc = (AbstractDocument)tfImei.getDocument();
absDoc.setDocumentFilter(docFilter);
这将只过滤到数字,长度为14!