documentFilter.insert never called

时间秒杀一切 提交于 2019-12-24 12:04:07

问题


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);
}

回答1:


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

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

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

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

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



来源:https://stackoverflow.com/questions/6846375/documentfilter-insertstring-is-never-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!