problem with JTextPane and StateInvariantError
Hi. I am having a problem with JTextPanes and changing only certain text to bold. I am writing a chat program and would like to allow users to make certain text in their entries bold. The best way I can think of to do this is to add <b> and </b> tags to the beginning and end of any text that is to be bold. When the other client receives the message, the program will take out all of the <b> and </b> tags and display any text between them as bold (or italic with <i> and </i>). I've searched the forums a lot and figured out several ways to make the text bold, and several ways to determine which text is bold before sending the text, but none that work together. Currently, I add the bold tags with this code: (note: messageDoc is a StyledDocument and messageText is a JTextPane)
public String getMessageText(){
String text =null;
boolean bold = false, italic =false;
for (int i = 0; i < messageDoc.getLength(); i++){
messageText.setCaretPosition(i);
if (StyleConstants.isBold(messageDoc.getCharacterElement(i).getAttributes()) && !bold){
bold =true;
if (text !=null){
text = text +"<b>";
}
else{
text ="<b>";
}
}
elseif (StyleConstants.isBold(messageDoc.getCharacterElement(i).getAttributes()) && bold){
// Do nothing
}
elseif (!StyleConstants.isBold(messageDoc.getCharacterElement(i).getAttributes()) && bold){
bold =false;
if (text !=null){
text = text +"</b>";
}
else{
text ="</b>";
}
}
try{
if (text !=null){
text = text + messageDoc.getText(i,1);
}
else{
text = messageDoc.getText(i, 1);
}
}
catch (BadLocationException e){
System.out.println("An error occurred while getting the text from the message document");
e.printStackTrace();
}
}
return text;
}// end getMessageText()
When the message is sent to the other client, the program searches through the received message and changes the text between the bold tags to bold. This seems as if it should work, but as soon as I click on the bold button, I get a StateInvariantError. The code for my button is:
publicvoid actionPerformed(ActionEvent evt){
if (evt.getSource() == bold){
MutableAttributeSet bold =new SimpleAttributeSet();
StyleConstants.setBold(bold,true);
messageText.getStyledDocument().setCharacterAttributes(messageText.getSelectionStart(), messageText.getSelectionStart() - messageText.getSelectionEnd() - 1, bold,false);
}
}//end actionPerformed()
Can anyone help me to figure out why this error is being thrown? I have searched for a while to figure out this way of doing what I'm trying to do and I've found out that a StateInvariantError has been reported as a bug in several different circumstances but not in relation to this. Or, if there is a better way to add and check the style of the text that would be great as well. Any help is much appreciated, thanks in advance.

