Java Swing How to - Show HTML with bullet point in JEditorPane








Question

We would like to know how to show HTML with bullet point in JEditorPane.

Answer

import java.awt.GridLayout;
/*w  w  w  .  j a  v  a2  s  .  c  o m*/
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;

public class Main {
  public JComponent makeEditorPane(String bullet) {
    JEditorPane pane = new JEditorPane();
    pane.setContentType("text/html");
    pane.setEditable(false);
    if (bullet != null) {
      HTMLEditorKit htmlEditorKit = (HTMLEditorKit) pane.getEditorKit();
      StyleSheet styleSheet = htmlEditorKit.getStyleSheet();
      String u = "http://i.stack.imgur.com/jV29K.png";
      styleSheet.addRule(String.format(
          "ul{list-style-image:url(%s);margin:0px 20px;", u));
      // styleSheet.addRule("ul{list-style-type:disc;margin:0px 20px;}");

    }
    pane.setText("<html><h1>Heading</h1>Text<ul><li>Bullet point</li></ul></html>");
    return pane;
  }

  public JComponent makeUI() {
    JPanel p = new JPanel(new GridLayout(2, 1));
    p.add(new JScrollPane(makeEditorPane(null)));
    p.add(new JScrollPane(makeEditorPane("bullet.png")));
    return p;
  }

  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    f.getContentPane().add(new Main().makeUI());
    f.setSize(320, 320);
    f.setVisible(true);
  }
}