java.lang.IllegalStateException 在 TextArea、Java 中使用文档侦听器时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2788779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.lang.IllegalStateException while using Document Listener in TextArea, Java
提问by Sunil Kumar Sahoo
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.
在这种情况下,我在 textarea 中设置文本时发现了以下错误。不知道怎么解决。
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.
我认为问题是在文档中设置文本或在文档侦听器中设置文档。但我不知道如何解决这个问题。请帮我解决这个问题。
回答by Chadwick
You cannot modify the document inside the DocumentListener. Write a custom Document instead, which overrides the insertString() or remove() methods.
您不能修改 DocumentListener 内的文档。而是编写一个自定义文档,它会覆盖 insertString() 或 remove() 方法。
From Java Tutorials: How to write a DocumentListener
来自 Java 教程:如何编写 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 Documentfor details.
文档侦听器不应修改文档内容;到侦听器收到更改通知时,更改已经完成。相反,编写一个自定义文档来覆盖 insertString 或 remove 方法,或两者兼而有之。有关详细信息,请参阅侦听文档的更改。
回答by Derek
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.
如果您想在侦听器中进行变异,您可以启动一个单独的线程,稍后使用 SwingUtilities.invokeLater 来完成。要小心,因为来自单独线程的修改将再次调用侦听器,因此在启动线程之前设置一个布尔值,如果设置了立即从侦听器返回,并在单独线程中完成修改后重置它。

