Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

swing - java.lang.IllegalStateException while using Document Listener in TextArea, Java

DocumentListener dl = new MessageDocumentListener();
((AbstractDocument) nboxArea.getDocument()).setDocumentFilter(new DocumentFilter() {
    public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
        string = string.replaceAll("", "");
        super.insertString(fb, offset, string,(javax.swing.text.AttributeSet) attr);
    }

    public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
        text = text.replaceAll("", "");
        //TODO must do something here
        super.replace(fb, offset, length, text,(javax.swing.text.AttributeSet) attrs);
    }
});

JTextArea evArea = (JTextArea) c;
evArea.getDocument().removeDocumentListener(dl);
evArea.setText(originalMessage);

In this case I found the following error during set text in textarea. I do not know how to resolve.

Exception in thread "AWT-EventQueue-0" 
java.lang.IllegalStateException: Attempt to mutate in notification

I think the problem is to set text in document or setting document in document listener. But I do not know how to solve this. Please help me to solve this issue.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You cannot modify the document inside the DocumentListener. Write a custom Document instead, which overrides the insertString() or remove() methods.

From Java Tutorials: How to write a DocumentListener

Document listeners should not modify the contents of the document; The change is already complete by the time the listener is notified of the change. Instead, write a custom document that overrides the insertString or remove methods, or both. See Listening for Changes on a Document for details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...