gpt4 book ai didi

Java JTextField 长度和过滤器

转载 作者:行者123 更新时间:2023-11-30 03:10:20 26 4
gpt4 key购买 nike

我正在尝试创建 Java IMEI 校验和计算器。校验和是 IMEI 15 位数字中的最后一位数字。

因此,我需要创建 JTextField,它限制为 14 个字符,并且仅限于数字!

对于 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 个字符和数字?

最佳答案

For the 14 characters limitation I've made a class extends PlainDocument as follow:

这是一种较旧的方法。较新的方法是使用 DocumentFilter。查看 Swing 教程中关于 Implementing a DocumentFilter 的部分一个工作示例。

For the digits only I've tried to use DocumentFilter like this. it do the job for the digits only but it cancel the 14 digits limitation.

不要使用自定义文档和文档过滤器。

相反,您可以将这些功能合并到一个 DocumentFilter 中。

或者对于更简单的解决方案,您可以使用JFormattedTextField。您可以指定一个掩码来控制位数和每个数字的类型:

MaskFormatter format = new MaskFormatter( "##############" );
JFormattedTextField ftf = new JFormattedTextField( mf );

本教程中有一个关于如何使用文本字段的部分,以获取更多信息和示例。

要获得更灵活的方法,您可能需要查看 Chaining Document Filters 。它允许您将多个文档过滤器合并到一个过滤器中,这样如果任何编辑失败,插入就会被阻止。这使您可以创建可在不同情况下使用的可重用过滤器。

关于Java JTextField 长度和过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33751343/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com