I am having a problem with updating documents in JTextPane. I have a
textPane. Whenever I type something in the textPane, I want to change the
color of the text just entered. The problem is when I get an event in
insertUpdate(), I can't call remove or insert again. If I do, an
IllegalStateException is thrown. What can I do to get around this problem?
Thanks in advance.
Here is part of my documentListener and the exception stack trace.
class MyDocumentListener implements DocumentListener{
public void insertUpdate(DocumentEvent e){
int offset = e.getOffset();
int length = e.getLength();
Document doc = e.getDocument();
try{
String text = doc.getText(offset, length);
System.out.println("inserted " + text);
doc.remove(offset, length);
MutableAttributeSet mas = new SimpleAttributeSet();
StyleConstants.setForeground(mas, Color.red);
doc.insertString(offset, text, mas);
}
catch(BadLocationException ble){
ble.printStackTrace();
}
}
Exception occurred during event dispatching:
java.lang.IllegalStateException: Attempt to mutate in notification
at javax.swing.text.AbstractDocument.writeLock(Unknown Source)
at javax.swing.text.AbstractDocument.insertString(Unknown Source)
at
MyDocumentListener.insertUpdate(ScrollableColoredTextPane.java:72)
Let a class, e.g. ColorDocument extend DefaultStyledDocument
override the method insertString(....) like this :
public void insertString(int offs, String str, AttributeSet a) throws
BadLocationException
{
MutableAttributeSet mas = new SimpleAttributeSet();
StyleConstants.setForeground(mas, java.awt.Color.red);
super.insertString(offs,str,mas);
}
Insert a ColorDocument object in your TextPane like this :
getJTextPane1().setDocument(new ColorDocument());
Et voila
hope this helps
Danny