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

12,942

Solution 1

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.

Solution 2

If you want to mutate in the listener you can launch a separate thread to do it later with SwingUtilities.invokeLater. Be careful because the modifications from the separate thread will call the listener again, so set a boolean before launching the thread, return immediately from the listener if it is set and reset it after the modifications have been done in the separate thread.

Share:
12,942
Sunil Kumar Sahoo
Author by

Sunil Kumar Sahoo

Please have a look on my career2.0 profile to know more about me. For source code follow me on github For articles follow me on Medium Thanks Sunil Kumar Sahoo Email Address [email protected]

Updated on July 19, 2022

Comments

  • Sunil Kumar Sahoo
    Sunil Kumar Sahoo almost 2 years
    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("\t", "");
            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("\t", "");
            //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.