Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

showing images on jeditorpane (java swing)

I have a JEditorPane created by this way:

JEditorPane pane = new JEditorPane("text/html", "<font face='Arial'>" + my_text_to_show + "<img src='/root/img.gif'/>" + "</font>");

I put this pane on a JFrame.

Text is shown correctly, but I can't see the picture, there is only a square indicating that there should be an image (i.e.: "broken image" shown by browsers when picture has not been found)

like image 360
Giancarlo Avatar asked Feb 21 '09 13:02

Giancarlo


2 Answers

You have to provide type, and get the resource. That's all. My tested example, but I'm not sure about formating. Hope it helps:

import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JFrame;

public class Test extends JFrame {

    public static void main(String[] args) throws Exception {
        Test.createAndShowGUI();
    }

    private static void createAndShowGUI() throws IOException {

        JFrame.setDefaultLookAndFeelDecorated(true); 

        JFrame frame = new JFrame("HelloWorldSwing");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        String imgsrc = 
            Test.class.getClassLoader().getSystemResource("a.jpg").toString();
        frame.getContentPane().add(new JEditorPane("text/html",
            "<html><img src='"+imgsrc+"' width=200height=200></img>"));
        frame.pack();

        frame.setVisible(true);
    }
}
like image 61
michal Avatar answered Sep 21 '22 20:09

michal


The JEditorPane is using HTMLDocument.getBase to locate relative urls as well, so if you are displaying content from a directory, make sure to set the base on the html document so it resolves urls relative to the base directory.

Depending on where that image actually is, you might want to extend HTMLEditorKit+HTMLFactory+ImageView and provide a custom implementation of ImageView, which is responsible for mapping the attribute URL to the image URL, too.

like image 34
John Gardner Avatar answered Sep 22 '22 20:09

John Gardner