Further anecdotes from Java Hate Land
Style is a class that inherits from MutableAttributeSet which conforms to AttributeSet. An AttributeSet contains key-value pairs describing character attributes, which works okay. However, Style contains additional state about character attributes that is seemingly completely separate from the state held by its superclass. Using the interface from AttributeSet to set character attributes yields no result whatsoever – the resulting text is unstyled.
Style s = new Style();
s.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
// Rendering text using s yields plain text, no formatting.
To actually set the style of a Style, you use the class StyleConstants’s static methods set[type of attribute](MutableAttributeSet, newValue), like so:
Style s = new Style();
StyleConstants.setUnderline(s, true);
Recall that AttributedString does not inherit from String. I’m beginning to believe that the Java designers never realized what object orientation is and just add inheritance to classes where it sounds good.
There seems to be no way whatsoever to represent styled text in Java that is in any way portable across the Java API. AttributedString only works with printing; AttributedCharacterIterator is the only way to get text and style out of the AttributedString; Style is used by the UI to represent style but while it actually inherits from the same class as the internal style representation in AttributedCharacterIterator, it’s actually completely incompatible. I’ve seen even more ways to represent style, but haven’t used them so I can’t recall them at the moment.
Right now, I’m going through hell to be able to get a formatted text representation of a model class of mine, being able to either append it to a JTextPane or send it directly to the printer, and later being able to extract the styled text from the JTextPane and send it to the printer. The text is going through at least three different representations of style on the way.
Please, for the love of god, tell me that I’m missing something blatantly obvious that makes this make any sense whatsoever.