在TextArea,Java中使用Document Listener时出现java.lang.IllegalStateException

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); 

在这种情况下,我在textarea中设置文本期间发现以下错误。 我不知道如何解决。

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

我认为问题是在文档中设置文本或在文档监听器中设置文档。 但我不知道如何解决这个问题。 请帮我解决这个问题。

您无法修改DocumentListener中的文档。 编写一个自定义文档,它会覆盖insertString()或remove()方法。

从Java教程: 如何编写DocumentListener

文档监听器不应修改文档的内容; 在收听者收到更改通知时,更改已完成。 而是编写一个自定义文档来覆盖insertString或删除方法,或两者​​兼而有之。 有关详细信息,请参阅侦听文档的更改 。

如果要在侦听器中进行变异,可以启动一个单独的线程,以便稍后使用SwingUtilities.invokeLater执行此操作。 要小心,因为来自单独线程的修改将再次调用侦听器,因此在启动线程之前设置布尔值,如果设置了则立即从侦听器返回,并在单独线程中完成修改后重置它。