Re: How do I handle styled text elegantly? --- now have working code
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);
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.