Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 792
OneMoreVladimir Avatar asked Jul 27 '11 13:07

OneMoreVladimir


1 Answers

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.

like image 78
camickr Avatar answered Nov 12 '22 09:11

camickr