题
我想显示的JLabel其具有文本的几行和图像,如下所示:
String html = "<html> hello </br> <img src = \"/absolute/path/here\" height = \"30\" width =\"40\"/> </html>";
JLabel l = new JLabel(html);
对于像我得到的是一个破碎的形象,是有可能的JLabel里面嵌套的img标签?
编辑: 我想多个图像添加到JLabel的,所以我不觉得用一个ImageIcon将在这里做的。
由于
解决方案
相反然后尝试对一个单一的JLabel为什么不能简单地具有许多的JLabel,每一个图像的多个图像(如uthark所述),然后组的所有标签一同在一个单一的JPanel。这应该给你你正在寻找只有很少的额外复杂性的影响。
其他提示
File f = new File("C:\image.jpg");
jLabel1.setText("<html><img src=\"file:"+f.toString()+"\">");
这对我的作品。这很简单,并给出可能把你想要的任何数量的图像,不只是一个形象的图标。它不工作不带引号。
For the image all I get is a broken image, is it possible to nest img tags inside a JLabel
它的是强>可以显示在JLabel的文本图像(一个或多个)。你得到破碎的形象,因为的的路径不正确的。你需要要么file:
前缀您的路径或最好获取Java与class.getResource("/your/path")
来为你做它。这里是一个工作例子中,只需要插入有效的资源的路径。
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);
}
}
有关在Java更复杂的HTML,我建议 xhtmlrenderer
使用一个JEditorPane显示HTML。您可以更改背景,前景,字体等,所以它看起来像一个标签。
在上述方法似乎不工作了。
看来你现在在img
标签使用的实际URI。
事情对我的工作有"<img src=\"" + new File(...).toURI() + "\">"
。
嵌入式图像未在HTML支持。因此,你必须使用或的setIcon提供一个ImageIcon与JLabel的构造函数;在HTML不能有一个IMG标记。
JLabel imageLabel =
new JLabel(labelText,
new ImageIcon("path/to/image.gif"),
JLabel.CENTER);
在你的情况,你需要使用的JTextPane 以显示HTML。参见教程这里