【问题标题】:How can I set fiscal code document filter in JTextField如何在 JTextField 中设置财务代码文档过滤器
【发布时间】:2016-03-10 16:40:15
【问题描述】:

我正在使用 Java swing 程序。我想在我的 JPanel 中插入一个具有限制字符数的 JTextFieldFormat,并将所有文本转换为 UPPER 文本。 所以我已经构建了这段代码:

textCodiceFiscale = new JTextField();
textCodiceFiscale.setDocument(new PersonalizzaJtextField(numberCharacter));
DocumentFilter filter = new UppercaseDocumentFilter();
        ((AbstractDocument) textCodiceFiscale.getDocument()).setDocumentFilter(filter);

这是 UppercaseDocumentFilter 类:

class UppercaseDocumentFilter extends DocumentFilter {
    public void insertString(DocumentFilter.FilterBypass fb, int offset,
        String text, AttributeSet attr) throws BadLocationException {

    fb.insertString(offset, text.toUpperCase(), attr);
    }

    public void replace(DocumentFilter.FilterBypass fb, int offset, int length,
        String text, AttributeSet attrs) throws BadLocationException {

    fb.replace(offset, length, text.toUpperCase(), attrs);
    }
}

这是 PersonalizzaJTextField 类:

public class PersonalizzaJtextField extends PlainDocument {

    //private StringBuffer cache = new StringBuffer();
    private int lunghezzaMax;

    public PersonalizzaJtextField(int lunghezzaMax){
        super();
        this.lunghezzaMax = lunghezzaMax;       
    }

    public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException{
        if (str == null)
            return;

        if ((getLength() + str.length()) <= lunghezzaMax) {
            super.insertString(offset, str, attr);
        }   
    }
}

现在有两个问题:

1) 使用此代码,我只能在 JTextField 中插入 UPPER 字符,但我在第二行限制字符数,不起作用。

2)我想为这个JTextField创建一个模板,我必须在这个模式下插入数字或文本:

6 个字符 2 个数字 1 个字符 2 个数字 1 个字符 3 个数字 1 个字符。

可以这样做吗?

【问题讨论】:

  • 不要使用自定义文档!!!只需使用DocumentFilter 并将这两个条件组合到过滤器中。首先你检查尺寸。如果更大,则退出。否则,在插入之前将文本转换为大写。

标签: java swing jtextfield documentfilter


【解决方案1】:

我想为这个 JTextField 创建一个模板,我必须在这种模式下插入数字或文本:

使用 JFormattedTextField。您可以使用 MaskFormatter 让 JFormattedTextField 为您进行编辑。使用适当的掩码,您可以指定数字或大写字符。

阅读 How to Use Formatted Text Fields 上的 Swing 教程部分,了解更多信息和示例。

顺便说一句,格式化文本字段会使用 MaskFormatter 自动为您创建 DocumentFilter,因此您需要一个自定义过滤器。

为教程添加书签。在关于此主题的最后一个问题中,您还获得了指向教程的链接。使用 Swing 基础教程。

【讨论】:

  • 非常感谢。我可以发布代码来执行此操作吗?
  • @bircastri,您可以编辑您的问题以显示您使用的最终代码。
猜你喜欢
  • 2021-01-02
  • 1970-01-01
  • 2014-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-10
相关资源
最近更新 更多