java - Swing 通过 ContentType 插入图像 ("text/html");

标签 java html image swing jtextcomponent

我编写了以下代码:

JDialog helpDialog = new JDialog();
helpDialog.setTitle("Help");
helpDialog.setResizable(false);
helpDialog.setAlwaysOnTop(true);
helpDialog.setSize(393, 43);

help.setSize(195,195);
help.setEditable(false);
help.setFont(new Font("Arial", Font.PLAIN, 24));
String txt = "<b><big>"+ "Help Page " +"</big></b>" + "<br/>" + 
        " <img src= \" ..\\image.jpg \" alt= \" Logo \" height= \"  \" width=\" 42 \"> ";
help.setContentType("text/html");
help.setText(txt);
help.setCaretPosition(0);
helpDialog.add(help);

helpDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
helpDialog.pack();
helpDialog.setVisible(true);
//Window in center of the display not in the left top corner
helpDialog.setLocationRelativeTo(null);

此对话框只是为了通知用户。我想通过 String txt = "<b><big>"+ "Help Page " +"</big></b>" + "<br/>" + " <img src= \" ..\\image.jpg \" alt= \" Logo \" height= \" \" width=\" 42 \"> "; 添加图像,但是即使图像位于 scr 中,也不会显示图像文件夹。

有什么建议可以把它放在哪里吗?

感谢您的回答!

最佳答案

尝试一些更像...

<img src='" + getClass().getResource("/path/to/image/image.jpg").toString() + "' .../>

相反...

您的代码无法运行的两个主要原因...

  1. 构建应用程序时,src 目录将不存在,并且图像将包含在生成的 Jar 文件中(假设您正在使用 Netbeans 之类的东西或手动构建它,否则,Eclipse 将要求将图像文件放入 resources 目录中)。这意味着资源不能再以您可能习惯的正常方式作为文件引用,并且......
  2. ..\\image.jpg 不是 API 解析图像的有效 URL(基本上,它不知道如何找到它),除此之外,相对上下文是,嗯,上下文并且可能会改变......

例如

Battle

import java.awt.EventQueue;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ShowMeTheImage {

    public static void main(String[] args) {
        new ShowMeTheImage();
    }

    public ShowMeTheImage() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                String text = "<html><img src='" + getClass().getResource("/images/battle.jpg").toString() + "'/>";

                JOptionPane.showMessageDialog(null, text);
            }
        });
    }

}

关于java - Swing 通过 ContentType 插入图像 ("text/html");,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24361179/

相关文章:

iphone - 从磁盘加载图像时的 ScrollView 和表格 View 性能

image - 我的 yarn 朝向哪个方向?

java - 在 Object.<init> (hprof) 中花费的时间

java - 从 Java 线程调用 C 函数后,整个 Java 应用程序变得无响应

java - CentOS 5安装Java错误

html - 在 wordpress 后端定位特定的移动页面

html - 带有两个垂直响应图像的整页,链接没有背景

java - Postgres JDBC 驱动程序 `org.postgresql.ds.PGSimpleDataSource` 是线程安全的吗?

javascript - Polymer 自定义元素 Shadow DOM 问题

jquery - 在 jQuery 中,我如何将左对齐样式附加到所有元素?