6

我正在尝试显示一个具有几行文本和图像的 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 不会。

谢谢

4

7 回答 7

5

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

于 2011-01-04T18:29:14.623 回答
5
File f = new File("C:\image.jpg"); 
jLabel1.setText("<html><img src=\"file:"+f.toString()+"\">");

这对我有用。它很简单,可以放置任意数量的图像,而不仅仅是一个图像图标。没有引号就不行。

于 2012-08-22T16:31:46.583 回答
2

除非您对 JEditorPane 感到满意,否则您基本上是在 Swing 中查看完整的网络浏览器。

理想情况下,您会使用 JWebPane,它是一个作为 Swing 组件的 WebKit 视图,但它还没有推出。我能找到的最新信息是这篇文。

DJ 项目允许在 Swing 中嵌入平台的本机浏览器。它在 Windows 上使用 Internet Explorer,在 Linux 上使用 XULRunner。它不支持 Mac。

于 2010-03-20T23:53:53.230 回答
1

使用 JEditorPane 显示 HTML。您可以更改背景、前景、字体等,使其看起来像一个标签。

于 2010-03-20T20:08:29.170 回答
1

与其尝试在单个 JLabel 上拥有多个图像,为什么不简单地拥有多个 JLabel,每个 JLabel 都有一个图像(如 uthark 所述),然后将所有标签组合在一个 JPanel 上。这应该会给您带来您正在寻找的效果,并且只需要最小的额外复杂性。

于 2010-03-20T23:59:40.500 回答
1

上述方法似乎不再起作用。

看来您现在必须在img标签中使用实际的 URI。

事情对我有用"<img src=\"" + new File(...).toURI() + "\">"

于 2018-06-05T10:05:14.050 回答
0

HTML 不支持嵌入的图像。因此,您必须使用 setIcon 或将 ImageIcon 提供给 JLabel 构造函数;HTML 不能有 IMG 标记。

  JLabel imageLabel =
  new JLabel(labelText,
             new ImageIcon("path/to/image.gif"),
             JLabel.CENTER);

在您的情况下,您需要使用JTextPane来显示 HTML。看这里的教程

于 2010-03-20T19:54:10.510 回答