Display images on jeditorpane (java swing)
I have a JEditorPane created this way:
JEditorPane pane = new JEditorPane("text/html", "<font face='Arial'>" + my_text_to_show + "<img src='/root/img.gif'/>" + "</font>"); I put this panel in a JFrame.
The text is displayed correctly, but I do not see the image, there is only a square indicating that there should be an image (that is: a βbroken imageβ displayed by browsers when the image was not found)
You must specify the type and get the resource. All this. My tested example, but I'm not sure about the formation. Hope this 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); } } JEditorPane uses HTMLDocument.getBase to search for relative URLs, so if you display content from a directory, be sure to set the base in the html document so that it resolves URLs relative to the base directory.
Depending on where the image is in fact, you can extend HTMLEditorKit + HTMLFactory + ImageView and provide a custom implementation of ImageView, which is also responsible for matching the attribute URL with the image URL.
None of the above worked for me, however 'imgsrc = new File("passport.jpg").toURL().toExternalForm();' allows me to try so that each image in html has a preceding "file:" so that it now reads:
<img src="file:passport.jpg" /> And it works great for me.
If you want to specify a relative path to the image.
Let's say your project folder structure looks like this:
sample_project/imagessample_project/images/loading.gifsample_project/srcsampler_project/src/package_name
Now the image tag will look like this:"<img src='file:images/loading.gif' width='100' height='100'>"
Yaay!
I used this when I was working at netbeans, but it was working. I think a little modification, if the program should work outside of netbeans,
String imgsrc=""; try { imgsrc = new File("passport.jpg").toURL().toExternalForm(); } catch (MalformedURLException ex) { Logger.getLogger(EntityManager.class.getName()).log(Level.SEVERE, null, ex); } //System.out.println(imgsrc); use this to check html = "<img src='" + imgsrc + "' alt='' name='passport' width='74' height='85' /><br />"; //use the html ... if you run from a jar, the image file should be on the same directory level ... ... in fact, the image file should be in the same directory as your entry.