Java Swing How to - Align images in the text in JEditorPane








Question

We would like to know how to align images in the text in JEditorPane.

Answer

import java.awt.BorderLayout;
//from   ww  w .  j  a  va 2s .  c  o  m
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;

public class Main extends JFrame {
  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationByPlatform(true);

    JEditorPane editPane = new JEditorPane();
    JScrollPane scrollPane = new JScrollPane(editPane);

    editPane.setContentType("text/html");

    editPane
        .setText("<html><p style = \"text-align:center;\">Hello there, How you doing ?<img src = "
            + "\"http://www.java2s.com/style/download.png"
            + "\" alt = \"pic\" width = \"15\" height = \"15\" />test test test"
            + "<br />I hope this is what you wanted!! "
            + "<img src =  \"http://www.java2s.com/style/download.png"
            + "\" alt = \"pic\" width = \"15\" height = \"15\" /> this is a test.</p></html>\n");

    add(scrollPane, BorderLayout.CENTER);
    setSize(400, 300);
    setVisible(true);
  }

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