【问题标题】:java.lang.IllegalStateException while using Document Listener in TextArea, Java在 Java 的 TextArea 中使用 Document Listener 时出现 java.lang.IllegalStateException
【发布时间】:2011-02-16 20:13:01
【问题描述】:
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

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

【问题讨论】:

    标签: java swing listener


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您不能在 DocumentListener 中修改文档。改为编写自定义 Document,它会覆盖 insertString() 或 remove() 方法。

      来自 Java 教程:How to write a DocumentListener

      文档监听器不应该修改文档的内容;到侦听器收到更改通知时,更改已经完成。相反,编写一个自定义文档来覆盖 insertString 或 remove 方法,或两者​​兼而有之。详情请见Listening for Changes on a Document

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-09
        • 1970-01-01
        • 2014-07-03
        • 2020-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多