Java Swing How to - Preserve formatting on empty HTML lines in JEditorPane








Question

We would like to know how to preserve formatting on empty HTML lines in JEditorPane.

Answer

import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.text.AttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.html.HTMLEditorKit;
//  w w w  . j  a  v  a2  s. com
public class Main {
  JEditorPane jep = new JEditorPane();

  public Main() {
    String html = "<html><head></head><body>"
        + "<p style = \"font-weight:bold; color: blue\">Line 1</p><br />"
        + "<p style = \"font-weight:bold; color: red\"></p><br />"
        + "<p style = \"font-weight:bold; color: green\">Line 3</p>"
        + "</body></html>";

    jep.setContentType("text/html");
    jep.setText(html);

    JFrame frame = new JFrame();
    frame.getContentPane().add(jep);
    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    System.out.println("Line 3 is " + isInputAttributeBold());
    jep.getCaret().setDot(8);
    System.out.println("Line 2 is " + isInputAttributeBold());
  }

  private boolean isInputAttributeBold() {
    AttributeSet attSet = ((HTMLEditorKit) jep.getEditorKit())
        .getInputAttributes();
    return StyleConstants.isBold(attSet);
  }

  public static void main(String[] args) {
    new Main();
  }
}