How to add stylesheet information to a JEditorPane

Did you know that you can use CSS styles when displaying HTML in a Java Swing application? It's pretty cool, and it can help spice up any simple HTML you may currently be showing in a Java-based editor or viewer. In this tutorial I'll share some source code that shows how this works.

If you haven't done it already in your own code, the first thing you need to do is create a JEditorPane, apply an HTMLEditorKit to your JEditorPane, then add it to a JScrollPane like this:

// create a JEditorPane
JEditorPane jEditorPane = new JEditorPane();

// make it read-only

// add a HTMLEditorKit to the editor pane
HTMLEditorKit kit = new HTMLEditorKit();

// now add it to a scroll pane
JScrollPane scrollPane = new JScrollPane(jEditorPane);

Add CSS styles with the StyleSheet class

Next, you can use the Java StyleSheet class to add some CSS style to the way your HTML is presented. Just get an instance of the StyleSheet class from your HTMLEditorKit, and then add some styles ("rules") to it, as shown in this code:

// add some styles to the html
StyleSheet styleSheet = kit.getStyleSheet();
styleSheet.addRule("body {color:#000; font-family:times; margin: 4px; }");
styleSheet.addRule("h1 {color: blue;}");
styleSheet.addRule("h2 {color: #ff0000;}");
styleSheet.addRule("pre {font : 10px monaco; color : black; background-color : #fafafa; }");

Display it all

Later on, when you're ready to render and display the HTML code, just get the Document from your HTMLEditorKit, set it on the JEditorPane, and then -- assuming you have one String that contains all the HTML you want to render -- just set that HTML on the JEditorPane using the JEditorPane setText method, like this:

// create a document, set it on the jeditorpane, then add the html
Document doc = kit.createDefaultDocument();

Here's an example of some HTML text, with the styles that I've shown above applied to the plain HTML:

As you can see, it's relatively simple to add some CSS styles like this to help spice up some plain HTML content. Using this technique, one portion of your code can render simple HTML content, and then you can add these CSS "rules" to make the HTML look the way you want it to look.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.