[英]Image not exporting when making runnable jar
In my project I use the system tray, when I compile the program everything is working fine and the icon that I use for the system tray shows up. 在我的项目中,我使用系统托盘,当我编译程序时,一切正常,并且显示用于系统托盘的图标。
The icon is placed in the project folder and the code related to the icon is 该图标位于项目文件夹中,并且与该图标相关的代码为
Image icon = Toolkit.getDefaultToolkit().getImage("Icon.png");
trayIcon = new TrayIcon(icon, "Program name", popup);
trayIcon.setImageAutoSize(true);
tray.add(trayIcon);
As I said, everything works find but when I export the project as a runnable jar the program will run but the icon will not show up, but it will just be blank. 正如我说的,一切正常,但是当我将项目导出为可运行的jar时,程序将运行,但图标不会显示,但它只是空白。
If you would like to load resources from your .jar file use getClass().getResource()
. 如果您想从.jar文件中加载资源,请使用
getClass().getResource()
。 That returns a URL with correct path. 这将返回具有正确路径的URL。
Image icon = ImageIO.read(getClass().getResource("image´s path"));
To access images in a jar, use Class.getResource()
. 要访问jar中的图像,请使用
Class.getResource()
。
I typically do something like this: 我通常会这样做:
InputStream stream = MyClass.class.getResourceAsStream("Icon.png");
if(stream == null) {
throw new RuntimeException("Icon.png not found.");
}
try {
return ImageIO.read(stream);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
stream.close();
} catch(IOException e) { }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.