Re: How do I handle styled text elegantly? --- now have working code
Posted By:
Ingo_Gruell
Posted On:
Wednesday, August 8, 2001 05:53 AM
OK, now I have some working code that does, what I need and
isn't quite as ugly as the code I began experimenting with.
The following code snippet assumes there is a Font called
myFont and some selected text in myJTextPane:
StyledDocument myDoc = myJTextPane.getStyledDocument();
Style myStyle = myDoc.addStyle(null, null);
StyleConstants.setBold(myStyle, myFont.isBold());
StyleConstants.setItalic(myStyle, myFont.isItalic());
StyleConstants.setFontFamily(s, myFont.getFamily());
StyleConstants.setFontSize(s, myFont.getSize());
int offset = myJTextPane.getSelectionStart();
int length = myJTextPane.getSelectionEnd() - offset;
myDoc.setCharacterAttributes(offset, length, myStyle, false);
Still, for object oriented programming this is rather awkward code.
If Font conformed to the Style interface, one
line of code would be do the job:
myJTextPane.getStyledDocument().setCharacterAttributes(myJTextPane.getSelectionStart(), (myJTextPane.getSelectionEnd() - myJTextPane.getSelectionStart()), myFont, false);
Unfortunately, that is not the case.