How to avoid IllegalStateException???
Hello!I try to apply Style dynamic to a JTextPane, but I get this Exception Al the time:
java.lang.IllegalStateException: Attempt to mutate in notification
at javax.swing.text.AbstractDocument.writeLock(AbstractDocument.java:1335)
at javax.swing.text.AbstractDocument.replace(AbstractDocument.java:660)
at fredrik.application.texteditor.JavaDocument.updateStyle(JavaDocument.java:223)
at fredrik.application.texteditor.TextEditorPane.updateStyle(TextEditorPane.java:148)
at fredrik.application.texteditor.UserInterfaceManager.updateStyle(UserInterfaceManager.java:937)
at fredrik.application.texteditor.CaretChangeListener.stateChanged(CaretChangeListener.java:18)
at javax.swing.text.DefaultCaret.fireStateChanged(DefaultCaret.java:634)
etc...
What I want to do is that when the user types certain words I would like to change the color for
those words like they do in TextPad or UltraEdit.
This is how it is made:
1) I have connect a CaretChangeListener to mu JTextPane, it will idicate when the user
have typed something.
2) After that the code below will be executed, called from the listener above. It will¨
change the new text into a certain Style if it is a reserved word.
public synchronized void updateStyle()
{
DefaultCaret defaultCaret = (DefaultCaret) jTextPane.getCaret();
int caretPos = defaultCaret.getDot();
String text = jTextPane.getText();
if(text.length() > 1)
{
int start = getStartIndex(text, caretPos);
String word = getWord(text, start, caretPos);
if(wordIsReserved(word))
{
AbstractDocument abstractDocument = (AbstractDocument) jTextPane.getDocument();
try
{
abstractDocument.readLock();
try
{
abstractDocument.replace(start, caretPos, word, (javax.swing.text.AttributeSet) jTextPane.getStyle("bluestyle") );
}
finally
{
abstractDocument.readUnlock();
}
}
catch(BadLocationException ble)
{
ble.printStackTrace();
}
}
}
}
public int getStartIndex(String text, int end)
{
int retValue = 0;
String temp = text.substring(0, end);
if(temp.lastIndexOf(" ") != -1)
{
retValue = temp.lastIndexOf(" ") + 1;
}
return retValue;
}
public String getWord(String text, int start, int end)
{
String word = text.substring(start, end);
return word;
}
public boolean wordIsReserved(String word)
{
boolean retValue = false;
//reservedWords is an array with reserved words..
for(int i = 0; i < reservedWords.length; i++)
{
if(word.equals(reservedWords[i]))
{
retValue = true;
break;
}
}
return retValue;
}
3) But it seems that I can't change the the jTextPane when I wan't.
So the question is how do I avoid IllegalStateException, or how do I wait for the right
state occur so I can do ny change?
Mvh
Fredrik
