Applying CSS to an HTML rendered JLabel

You can set a StyleSheet on an HTMLEditorKit. It is shared by all HTMLEditorKit instances.

This example shows you how to set the margins, colors and size of any h1 used to render HTML in your Swing components.

import javax.swing.text.html.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class Main extends JFrame {
   public Main(StyleSheet s) {
      getContentPane().setLayout(new FlowLayout());
      HTMLEditorKit kit = new HTMLEditorKit();
      final JLabel label = new JLabel("<html><h1>Socrates</h1></html>");
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
      setSize(300, 300);
   public static StyleSheet loadStyleSheet(InputStream is) throws IOException
      StyleSheet s = new StyleSheet();
      BufferedReader br = new BufferedReader(new InputStreamReader(is));
      s.loadRules(br, null);
      return s;
   public static void main(String[] args) throws Exception {
      StyleSheet s = loadStyleSheet(new FileInputStream("default.css"));
      (new Main(s)).show();


h1 {
   font-size:	24pt;
   font-weight:	bold;
   color:	red;
   margin-top:  10;
   margin-bottom:	10