Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can JLabel have img tags

I am trying to display a JLabel which has a few lines of text and an image as follows:

String html = "<html> hello </br> <img src = \"/absolute/path/here\" height = \"30\"  width =\"40\"/> </html>";
JLabel l = new JLabel(html);

For the image all I get is a broken image, is it possible to nest img tags inside a JLabel?

EDIT: I want to add multiple images to the JLabel so I don't think the use of an ImageIcon will do here.

Thanks

like image 852
Aly Avatar asked Mar 20 '10 19:03

Aly


2 Answers

For the image all I get is a broken image, is it possible to nest img tags inside a JLabel

It is possible to display image(s) in a JLabel's text. You are getting broken images because the path is not correct. You need to either prefix your path with file: or preferably get java to do it for you with class.getResource("/your/path"). Here is a working example, just insert valid resource paths.

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel; 

public class MultipleImagesExample
{

  public static void main(String[] args)
  {

      JFrame frame = new JFrame();
      frame.setLayout(new BorderLayout());
      JLabel label = new JLabel(
          "<html>"
          + "<img src=\""
          + MultipleImagesExample.class.getResource("/resource/path/to/image1")
          + "\">"
          + "<img src=\""
          + MultipleImagesExample.class.getResource("/resource/path/to/image2")
          + "\">"
          + "The text</html>");
      frame.add(label, BorderLayout.CENTER);
      frame.setBounds(100, 100, 200, 100);
      frame.setVisible(true);
   }

 }

For more complex HTML in java, I recommend xhtmlrenderer.

like image 141
brian_d Avatar answered Sep 19 '22 12:09

brian_d


File f = new File("C:\image.jpg"); 
jLabel1.setText("<html><img src=\"file:"+f.toString()+"\">");

This works for me. It's simple and gives possibility to put any number of images you want, not just one image icon. It's not working without quotation marks.

like image 44
daredesm Avatar answered Sep 22 '22 12:09

daredesm