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.

Main.java:

import javax.swing.text.html.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
   
public class Main extends JFrame {
   public Main(StyleSheet s) {
      getContentPane().setLayout(new FlowLayout());
  
      HTMLEditorKit kit = new HTMLEditorKit();
      kit.setStyleSheet(s);
 
      final JLabel label = new JLabel("<html><h1>Socrates</h1></html>");
      getContentPane().add(label);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      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);
      br.close();
  
      return s;
   }
  
   public static void main(String[] args) throws Exception {
      StyleSheet s = loadStyleSheet(new FileInputStream("default.css"));
 
      (new Main(s)).show();
   }
}

default.css:

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