【问题标题】:Document filter is not working in Java?文档过滤器在 Java 中不起作用?
【发布时间】:2011-11-23 13:09:15
【问题描述】:

文本字段超过10个字符na,必须显示错误。为此,我使用了文档过滤器:

JTextField field = (JTextField) txtFld;
AbstractDocument document = (AbstractDocument) field.getDocument();
document.setDocumentFilter(new DocumentSizeAndUppercaseFilter(10));

这是我的文档过滤器编码。我通过文档过滤器注册了文本字段。但这里什么都没有发生。如何使用文档过滤器?

DocumentSizeAndUppercaseFilter 类有错误消息。

【问题讨论】:

  • 您之前的 8 个问题都没有任何可接受的答案?

标签: java swing jtextfield


【解决方案1】:

如果没有看到DocumentSizeAndUppercaseFilter 的代码,我会怀疑您没有实现(/覆盖)DocumentFilterreplace 方法:

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

    ....
}

以下代码截图:


DocumentSizeAndUppercaseFilter的示例实现:

static class DocumentSizeAndUppercaseFilter extends DocumentFilter {

    private final int max;

    public DocumentSizeAndUppercaseFilter(int max) {
        this.max = max;
    }

    @Override
    public void insertString(DocumentFilter.FilterBypass fb, int offset,
                             String text, AttributeSet attr) 
            throws BadLocationException {
        if (fb.getDocument().getLength() + text.length() < max)
            super.insertString(fb, offset, text.toUpperCase(), attr);
        else 
            showError();
    }

    @Override
    public void replace(DocumentFilter.FilterBypass fb, int offset,
                        int length, String text, AttributeSet attrs)
            throws BadLocationException {
        int documentLength = fb.getDocument().getLength();
        if (documentLength - length + text.length() < max)
            super.replace(fb, offset, length, text.toUpperCase(), attrs);
        else 
            showError();
    }

    private void showError() {
        JOptionPane.showMessageDialog(null, "Too many characters entered");
    }
}

例如main:

public static void main(String[] args) {

    JTextField firstName = new JTextField();
    AbstractDocument d = (AbstractDocument) firstName.getDocument();
    d.setDocumentFilter(new DocumentSizeAndUppercaseFilter(10));

    JFrame frame = new JFrame("Test");
    frame.add(firstName);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200, 60);
    frame.setVisible(true);
}

【讨论】:

  • 你有没有试过我的例子。它不是按您希望的那样工作吗?
  • 应该工作(为我工作)!重写示例以满足您的需求。 现在插入太多字符时会显示错误消息。(还添加了屏幕截图)
  • +1 也适用于我,尽管我必须导入正确的 AttributeSet。 :-)
  • 对不起。我做错了..现在它可以正常工作了..非常感谢
  • 信息丰富的答案,它也适用于我的代码,感谢指导。
【解决方案2】:

从简单的开始。

Implementing a Document Filter 上的 Swing 教程部分有一个工作示例,可以完成您想要的一半。

【讨论】:

    猜你喜欢
    • 2014-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    • 1970-01-01
    • 2010-10-15
    • 2017-04-04
    • 2011-05-24
    相关资源
    最近更新 更多