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
fiziwig - 07 Aug 2006 21:10 GMT
Never mind. I figured it out:
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);