Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

updating document in JTextPane

9 views
Skip to first unread message

Anton An

unread,
Oct 17, 2000, 3:00:00 AM10/17/00
to
Hi all,

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)

Danny Foncke

unread,
Oct 25, 2000, 3:00:00 AM10/25/00
to
The easiest way of acomplishing this is to make a specialized Document
(in this case a StyledDocument)

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

0 new messages