I want to display HTML in a JEditorPane or JTextPane, but I want the style (font size) to come from the Look and Feel. Is there a way to do this, or do you have to use embedded HTML styling?
Here is an example:
epText = new JEditorPane("text/html", content);
StyleSheet ss = ((HTMLEditorKit)epText.getEditorKit()).getStyleSheet();
ss.addRule("p {font-size:" + FontManager.getManager().getFontSize() + "}");
HTMLEditorKit kit = (HTMLEditorKit) epText.getEditorKit();
kit.setStyleSheet(ss);
epText.setEditorKit(kit);
Whenever I set the editor kit, all text disappears. Do I need to set the text everytime?
Yes.
Dig into this snippet, from the Java API for HTMLEditorKit:
Customization from current LAF
HTML provides a well known set of features without exactly specifying the display characteristics. Swing has a theme mechanism for its look-and-feel implementations. It is desirable for the look-and-feel to feed display characteristics into the HTML views. An user with poor vision for example would want high contrast and larger than typical fonts.
The support for this is provided by the
StyleSheet
class. The presentation of the HTML can be heavily influenced by the setting of the StyleSheet property on the EditorKit.
Edit: when you set the Editor Kit, it de-installs the old kit and installs the new one. This changes the underlying model, which is why the text 'disappears'. Read the API for more info.
But you may not need to re-create the entire kit... just add a new sheet to your style.