我编写了以下代码:
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() + "' .../>
相反...
您的代码无法运行的两个主要原因...
- 构建应用程序时,
src
目录将不存在,并且图像将包含在生成的 Jar 文件中(假设您正在使用 Netbeans 之类的东西或手动构建它,否则,Eclipse 将要求将图像文件放入resources
目录中)。这意味着资源不能再以您可能习惯的正常方式作为文件引用,并且...... ..\\image.jpg
不是 API 解析图像的有效 URL(基本上,它不知道如何找到它),除此之外,相对上下文是,嗯,上下文并且可能会改变......
例如
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/