我在我的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。 –