views:

292

answers:

2

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?

+2  A: 

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.

Tim Drisdelle
I've updated my question to better show this comment.
jmcmahon
Thanks, this was very helpful.
jmcmahon
A: 

Call this from the main method after you set L&F.

public static void setDefaultStyle()
{
    // looks like WTF but that is the way to set default CSS
    StyleSheet sheet=new HTMLEditorKit().getStyleSheet();
    // add your rules
    sheet.addRule("...");
    sheet.addRule("...");
}

EDIT: At least this should work for JTextPane.

Ha