0

I am using eclipse juno for the java application and want to load an image on application and for that I am writing following code

 URL imageURL = LoginWindow.class.getClassLoader().getResource("resources/img/pause.png");

which gives the following error

Resource not found: resources/img/pause.png Exception in thread "main" java.lang.IllegalArgumentException: creating TrayIcon with null Image at java.awt.TrayIcon.(Unknown Source)

but if I put the image in the folder where my java file is and remove all path and give only "pause.png" then it works properly.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Uday A. Navapara
  • 1,237
  • 5
  • 20
  • 40

4 Answers4

4

The class loader that is obtained using that form of call would probably not be the context class loader intended for loading application resources. I would recommend instead:

LoginWindow lw = new LoginWindow();
// exactly as below, including leading /
URL url = lw.getClass().getResource("/resources/img/pause.png");
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
2

Get the Class Relative path from their you can refer to the the image

enter image description here

      ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    String imgUrl =classLoader.getResource(".").getPath()+   
                                       "../resources/img/pause.png";

By using the imgUrl you do your what operation you want to do .

loknath
  • 1,362
  • 16
  • 25
  • this is so useful but not give proper output it can not find the image.... it return following path Path is :- /D:/Project/Time%20Monitoring%20System/bin/../resources/img/pause.png – Uday A. Navapara Apr 19 '14 at 10:28
-1

Give the structure of your project please. If you have a Maven project, your code should be as follows:

URL imageURL = LoginWindow.class.getClassLoader().getResource("src/main/resources/img/pause.png");
njc
  • 111
  • 8
-1

try this if you are running in an applet

URL url = new URL(getCodeBase(), "resources/img/pause.png");
Hamid
  • 114
  • 1
  • 3
  • 1) There is no indication this is an applet. In fact ` Exception in thread "main" ` suggests a frame based app. 2) The `getResource(..)` method works exactly the same for an applet as it does for an application. – Andrew Thompson Apr 18 '14 at 04:59