简体   繁体   中英

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.

If you would like to load resources from your .jar file use getClass().getResource() . That returns a URL with correct path.

Image icon = ImageIO.read(getClass().getResource("image´s path"));

To access images in a jar, use 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) { }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM