File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Imageicon URL Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Imageicon URL" Watch "Imageicon URL" New topic

Imageicon URL

Atul Mishra
Ranch Hand

Joined: Jun 08, 2006
Posts: 140
Quick question regarding String url used for ImageIcon constructor.

I have a eclipse web project with src and webcontenet folders. I have a java file in -> in which I have the following code:

String url = "images/icon1.gif";
ImageIcon icon = new ImageIcon(Test.class.getResource(url),"Test icon");

The file icon.gif is under Webcontent/images directory.

this gives runtime exception: cannot locate file [gif file]. Why ? Where should I put the images for the jva code to access ? I prefer putting in this webcontent/images directory. Thanks all
Joe Ess

Joined: Oct 29, 2001
Posts: 9189

public URL getResource(String name)
. . .
This method delegates the call to its class loader, after making these changes to the resource name: if the resource name starts with "/", it is unchanged; otherwise, the package name is prepended to the resource name after converting "." to "/". If this object was loaded by the bootstrap loader, the call is delegated to ClassLoader.getSystemResource.


Your images must be on the classpath to be found with Class.getResource. Either change the image location or add the directory to the classpath.

[How To Ask Questions On JavaRanch]
Atul Mishra
Ranch Hand

Joined: Jun 08, 2006
Posts: 140
Thanks for your response.

I even tried using ImageIcon icon = new ImageIcon(url,"Test icon"); where url = ""; //for this if I put the complete path it works fine. [like C: etc]

But this file/app has to be deployed as a webapp and installed on server. Thats why I tried putting in webcontent folder and hence accessing it..

Any ideas ?
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
The File class has a method toURL that you can use.
I agree. Here's the link:
subject: Imageicon URL
It's not a secret anymore!