开发者

documentFilter.insert never called

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜