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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With