How to add a picture to the java project. When debugging, the picture is displayed, but after the project is assembled in the jar, there is no picture.

systemTray = SystemTray.getSystemTray(); Image image = Toolkit.getDefaultToolkit().getImage("src\\images\\logo-main2.png"); TrayIcon trayIcon = new TrayIcon(image , "GrindFM", popupMenu); trayIcon.setImageAutoSize(true); systemTray.add(trayIcon); 

enter image description here

enter image description here

  • Put the picture in the package and specify the absolute path to the picture starting from the package root: / mypackageroot / myblablabla /image.png - ezhov_da
  • Didn't quite understand what the path would be in my case? - razear

1 answer 1

The problem is that you load the resource from the disk, not from the jar. When you work in the dev environment, you launch the jar from where you can go through the folders on the disk and get to this picture. When you run it on another PC, there is no corresponding folder there. You need to use the resource loading from the classpath , to do this, change the code as follows

 systemTray = SystemTray.getSystemTray(); URL resource = getClass().getResource("images/logo-main2.png"); Image image = Toolkit.getDefaultToolkit().getImage(resource); TrayIcon trayIcon = new TrayIcon(image , "GrindFM", popupMenu); trayIcon.setImageAutoSize(true); systemTray.add(trayIcon); 

Everything should earn

  • Transferred along this path, it is not displayed all the way in jar Image image = new ImageIcon ("src \\ java \\ resources \\ logo-main2.png"). getImage (); - razear
  • Now this picture is in the class path, you need to load it now from the class path, you load the picture from the disk, the jar 'picture is looking outside itself, not inside, and when you load from the class path, you will search inside - Vyacheslav Gusser
  • You can load in more detail how from the class path. I added String path = "/resources/logo-main2.png"; PlayerRadio.class.getResourceAsStream (path); - razear
  • Almost correctly, in your example you need to remove / resources, and just leave logo-main2.png - Vyacheslav Gusser
  • String path = "logo-main2.png"; PlayerRadio.class.getResourceAsStream (path); Image image22 = new ImageIcon ("src \\ java \\ resources \\ logo-main2.png"). GetImage (); TrayIcon trayIcon = new TrayIcon (image22, "GrindFM", popupMenu); trayIcon.setImageAutoSize (true); systemTray.add (trayIcon); Vserovno does not see the picture in jar - razear