Question about MutableAttributeSet / Style / StyleConstants
I'm having a hard time figuring out how these are all interconnected. Specifically, I'm trying to implement a button that sets or clears bold on selected text depending on whether the first character of the selceted text is already bold or not.
StyledDocument doc = textRegion.getStyledDocument();
int offset = textRegion.getSelectionStart();
int length = textRegion.getSelectionEnd() - offset;
Style current = doc.getLogicalStyle(offset);
MutableAttributeSet attr =new SimpleAttributeSet();
if ( StyleConstants.isBold(current)){
StyleConstants.setBold(attr,false);
}else{
StyleConstants.setBold(attr,true);
}
doc.setCharacterAttributes(offset, length, attr,false);
But what it does is to set bold on no matter what. Obviously I'm not understanding how to find out if a given character in a StyledDocument is bold or not. How am I supposed to be doing this?
Thanks
--gary
[1340 byte] By [
fiziwiga] at [2007-10-3 2:14:06]

Another version that seems to me like it ought to work but doesn't
int offset = textRegion.getSelectionStart();
int length = textRegion.getSelectionEnd() - offset;
System.out.println("offset="+offset+" length="+length);
AttributeSet current = textRegion.getCharacterAttributes();
if (current==null) {
current = textRegion.getInputAttributes();
}
MutableAttributeSet attr = new SimpleAttributeSet();
if (current.getAttribute("bold")!=null) {
System.out.println("clear bold");
StyleConstants.setBold(attr, false);
} else {
System.out.println("set bold");
StyleConstants.setBold(attr,true);
}
textRegion.setCharacterAttributes(attr, false);
Does anyone else find it annoying that the Java documentation is only helpful if you already know the answer?
--gary
FWIW: This works:
int offset = textRegion.getSelectionStart();
int length = textRegion.getSelectionEnd() - offset;
AttributeSet current = textRegion.getCharacterAttributes();
if (current==null) {
current = textRegion.getInputAttributes();
}
MutableAttributeSet attr = new SimpleAttributeSet();
boolean bold = false;
if (current.getAttribute(StyleConstants.Bold)!=null) {
bold = (current.getAttribute(StyleConstants.Bold).toString()=="true") ? true : false;
}
if (bold) {
StyleConstants.setBold(attr, false);
} else {
StyleConstants.setBold(attr,true);
}
textRegion.setCharacterAttributes(attr, false);
--gary