我在我的GUI中有兩個JTextAreas,並且我在每個JTextArea上都有一個DocumentListener,我試圖做的是例如當我在文本區域編號1中鍵入abc時,它將採用該文檔文本以某種方式進行修改並將其輸出到JTextArea 2的文檔中。在Java GUI中的文檔模型
與我的監聽器我可以獲取源文檔得到一個錯誤
異常在線程 「AWT-EventQueue的 - 0」 java.lang.IllegalStateException:嘗試在通知變異
PLE幫助。
感謝
下面是一些代碼:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Maxi
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class Test {
static JFrame frame = new JFrame("CaesarEncipherGUI");
static JPanel panel = new JPanel();
static JTextArea area = new JTextArea(5,20);
static JTextArea area1 = new JTextArea(5,20);
static class MyDocumentListener2 implements DocumentListener {
public void insertUpdate(DocumentEvent e) {
updateLog(e,"");
}
public void removeUpdate(DocumentEvent e) {
updateLog(e,"");
}
public void changedUpdate(DocumentEvent e) {
}
public void updateLog(DocumentEvent e, String action){
Document doc = (Document)e.getDocument();
try{
System.out.println("Action detected "+doc.getProperty("type"));
String text = doc.getText(0, doc.getLength());
doc.insertString(0, "hey", null); //heres the line that throws the error.
//mutation of text here
}catch (BadLocationException catchme2){}
}
}
public static void main(String[] args){
area.getDocument().addDocumentListener(new MyDocumentListener2());
//initialize
frame.setResizable(false);
frame.setBounds(300, 300, 235, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.add(area);
panel.add(area1);
frame.add(panel);
frame.setSize(235,400);
frame.setVisible(true);
}
}
那麼,如果偵聽器在文檔1上並且您嘗試更改文檔2中的文本,是否會發生此錯誤?或者僅當您嘗試更改正在偵聽的相同文檔中的文本時。我猜想這將是後者,並且該問題在DocumentListener API中的「不保證訂單...」部分有詳細描述。一種解決方案是將代碼封裝在Runnable中,並通過'SwingUtilities.invokeLater(...)'將其排列在EDT上。 –
從我在線閱讀的內容看來,您並不認爲要更改文檔偵聽器中的文檔文本。然後,我會在哪裏執行文檔中的文本更改。 – user541597
同樣,您可以通過在EDT上排隊更改來完成此操作。另一個也許更好的解決方案是使用DocumentFilter。 –