Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

swing - 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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...