Java Swing How to - Style JTextPane with HTML and CSS








Question

We would like to know how to Style JTextPane with HTML and CSS.

Answer

import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.WindowConstants;
/*  w  w w.  ja  va2  s .  c om*/
public class Main {
  public static void main(String[] args) {
    String HTMLTEXT = "<html><head><style>.foot{color:red} .head{color:black}</style></head>"
        + "<span style='font-family:consolas'>java2s.com</span><br/>"
        + "<span style='font-family:tahoma'>java2s.com</span>";
    JTextPane textPane1 = new JTextPane();


    textPane1.setContentType("text/html");
    textPane1.setText(HTMLTEXT);

    JFrame f = new JFrame();
    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    f.getContentPane().add(new JScrollPane(textPane1));
    f.setSize(320, 240);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}