documentFilter.insert从未调用过 [英] documentFilter.insert never called

查看:121
本文介绍了documentFilter.insert从未调用过的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的JTextArea设置documentFilter。覆盖插入(...)方法后,我承认它永远不会被调用。怎么了?一段代码:

I'm trying to set a documentFilter for my JTextArea. Having overriden the insert(...) method I admitted that it is never called. What's wrong? A piece of code:

package jaba;

import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;

public class Main extends JFrame {
    public Main() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(640, 480);
        setLayout(new FlowLayout());
        add(txt);
        Document doc = txt.getDocument();
        if (doc instanceof AbstractDocument) {
            ((AbstractDocument)doc).setDocumentFilter(new DocumentFilter() {
                @Override
                public void insertString(DocumentFilter.FilterBypass fb, 
                        int offset, String string, AttributeSet att)
                throws BadLocationException {
                    if (string.toLowerCase().contains("ass")) {
                        super.insertString(fb, offset, "###", att);
                    } else {
                        super.insertString(fb, offset, string, att);
                    }
                }
            });
        } else {
            txt.setText("error setting filter");
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Main().setVisible(true);
            }
        });
    }

    private JTextArea txt = new JTextArea(40, 40);
}


推荐答案


覆盖插入(...)方法后,我承认它永远不会被调用。

Having overriden the insert(...) method I admitted that it is never called.

最终对Swing组件中的文本进行更改调用DocumentFilter的replace(...)方法。

Changes to the text in Swing components ultimately invoke the replace(...) method of the DocumentFilter.

只有在使用以下代码直接更新Document时才会调用insertString(...)方法:

The insertString(...) method is only invoked when you update the Document directly by using code like:

textField.getDocument().insertString(...);

所以你需要确保你也覆盖了DocumentFilter中的replace()方法。

So you need to make sure that you also override the replace() method in the DocumentFilter.

这篇关于documentFilter.insert从未调用过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆