簡體   English   中英

在TextArea,Java中使用Document Listener時出現java.lang.IllegalStateException

[英]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);

在這種情況下,我在textarea中設置文本期間發現以下錯誤。 我不知道該如何解決。

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

我認為問題是在文檔中設置文本或在文檔監聽器中設置文檔。 但我不知道如何解決這個問題。 請幫我解決這個問題。

您無法修改DocumentListener中的文檔。 編寫一個自定義文檔,它會覆蓋insertString()或remove()方法。

從Java教程: 如何編寫DocumentListener

文檔監聽器不應修改文檔的內容; 在收聽者收到更改通知時,更改已完成。 而是編寫一個自定義文檔來覆蓋insertString或刪除方法,或兩者​​兼而有之。 有關詳細信息,請參閱偵聽文檔的更改

如果要在偵聽器中進行變異,可以啟動一個單獨的線程,以便稍后使用SwingUtilities.invokeLater執行此操作。 要小心,因為來自單獨線程的修改將再次調用偵聽器,因此在啟動線程之前設置一個布爾值,如果設置了則立即從偵聽器返回,並在單獨線程中完成修改后重置它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM