我正在尝试将图像设置为JLabel,在我的项目中我有一个文件夹“images”,其中就是logo.png
我使用以下代码来获取它
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(new File("images/logo.png"));
} catch (IOException e1) {
e1.printStackTrace();
}
JLabel headerImage = new JLabel(new ImageIcon(myPicture));
这是eclipse中的工作文件,但是在runnable jar之外不会触发,除非它与文件夹中带有徽标文件的图像位于同一目录中。
所以我的问题是如何在.jar文件中打包图像并让这段代码引用它?
答案 0 :(得分:4)
您需要从类路径而不是从本地磁盘文件系统获取它。
假设图像实际上是一个包,并且该包与当前类位于同一个JAR中,那么这样做:
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(getClass().getResource("/images/Report.png"));
} catch (IOException e1) {
e1.printStackTrace();
}
JLabel headerImage = new JLabel(new ImageIcon(myPicture));
答案 1 :(得分:3)
试试这个对我来说很好用
ImageIO.read(getClass().getResource("images/logo.png"));
答案 2 :(得分:2)