[英]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("\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. 在这种情况下,我在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.
请帮我解决这个问题。
You cannot modify the document inside the DocumentListener. 您无法修改DocumentListener中的文档。 Write a custom Document instead, which overrides the insertString() or remove() methods.
编写一个自定义文档,它会覆盖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.
而是编写一个自定义文档来覆盖insertString或删除方法,或两者兼而有之。 See Listening for Changes on a Document for details.
有关详细信息,请参阅侦听文档的更改 。
If you want to mutate in the listener you can launch a separate thread to do it later with SwingUtilities.invokeLater. 如果要在侦听器中进行变异,可以启动一个单独的线程,以便稍后使用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.
要小心,因为来自单独线程的修改将再次调用侦听器,因此在启动线程之前设置一个布尔值,如果设置了则立即从侦听器返回,并在单独线程中完成修改后重置它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.