Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / GUI / September 2004

Tip: Looking for answers? Try searching our database.

ImageIcon not finding my images!

Thread view: 
Kane Bonnette - 21 Sep 2004 19:57 GMT
Hello,

So, I'm trying to use an ImageIcon to display some pictures in a JPanel
(which is itself inside a JFrame)
Unfortunately, my ImageIcon is blank. I made sure I'm using the proper
filename/path, and that the image is where I think it is.

my code looks like the following

...
ImageIcon pic0 = new ImageIcon("pic0.jpg");
JLabel pic0a = new JLabel(pic0);
JPanel panel = new JPanel();
panel.add(pic0a);
frame.getContentPane().add(panel);
...

anybody know what might be causing my picture not to display?

Kane Bonnette
Andrew Thompson - 21 Sep 2004 20:29 GMT
> So, I'm trying to use an ImageIcon to display some pictures in a JPanel
> (which is itself inside a JFrame)
> Unfortunately, my ImageIcon is blank. I made sure I'm using the proper
> filename/path, and that the image is where I think it is.

You may be sure, but let's ask Java..

> my code looks like the following
>
> ...
> ImageIcon pic0 = new ImageIcon("pic0.jpg");

URL thePic = this.getClass().getResource("pic0.jpg");
System.out.println("Pic URL is: " + thePic);

If that is 'null', Java cannot find your image.

OTOH, if it retrusn a valid URL, it might be that
the image has not loaded yet, but from memory,
when you construct a JLabel with ImageIcon, all
that is taken care of.

Signature

Andrew Thompson
http://www.PhySci.org/codes/  Web & IT Help
http://www.PhySci.org/  Open-source software suite
http://www.1point1C.org/  Science & Technology
http://www.lensescapes.com/  Images that escape the mundane

Kane Bonnette - 21 Sep 2004 23:17 GMT
...

> URL thePic = this.getClass().getResource("pic0.jpg");
> System.out.println("Pic URL is: " + thePic);
>
> If that is 'null', Java cannot find your image.

This turns out to be the issue. Now the question is, what do I need to do to
get Java to find my file?
I"ve placed the picture in the same folder as my source code and my .class
files, before I compile

I also need to use a relative path, since this has to be portable

> OTOH, if it retrusn a valid URL, it might be that
> the image has not loaded yet, but from memory,
> when you construct a JLabel with ImageIcon, all
> that is taken care of.
Paul Lutus - 21 Sep 2004 23:43 GMT
> ...
>>
[quoted text clipped - 9 lines]
>
> I also need to use a relative path, since this has to be portable

In that case, put it and your application in a jar file. This makes locating
the graphic must more likely. You are not likely to be able to use relative
addressing if the required elements are not packaged in some way. It's not
impossible, it's just a lot of effort when creating a jar file is simpler
and has other advantages as well.

Signature

Paul Lutus
http://www.arachnoid.com

Mark Murphy - 22 Sep 2004 04:43 GMT
> ...
>
[quoted text clipped - 7 lines]
> I"ve placed the picture in the same folder as my source code and my .class
> files, before I compile

Try printing:
String dir = System.getProperty("user.dir");

For example if you are using netbeans, netbeans will start Java from
it's home directory. If this is the case then you have to edit the class
path in the IDE or move your image to the location identified. Does the
program see the image when you run it from the command line & you have
the image with the source?

I had this problem too and banged my head against the wall for a long time.
Jacob - 22 Sep 2004 06:14 GMT
> This turns out to be the issue. Now the question is, what do I need to do to
> get Java to find my file?
> I"ve placed the picture in the same folder as my source code and my .class
> files, before I compile
>
> I also need to use a relative path, since this has to be portable

Icons should be accessed through the classpath as you indicate.
This means they should be located in your _destination_ directory
(along with your .class files) on your development machine, and
be bundled into the .jar if that's how you deploy. Typically you
set Make or Ant or your IDE up so that it _copies_ images (or make
a symbolic link) from your source area to your destination area.

Code to access an image via classpath:

  URL url = getClass().getResource ("/com/company/path/icon.gif");
  ImageIcon icon = new ImageIcon (url);
  JLabel label = new JLabel (icon);

Beware: Don't use backslash in the path. This is *not* a file name
(even if it looks like that). It is a _resource_ and Java chose the
slash as a delimiter.

Also: Don't forget the initial "/". This is a common error. Probably
because "jar -tf" don't report it.

Note: Most often images are accessed from within the
_current_ package (that is at least how you should organize it; don't
have one single /com/company/images/ repository). In this case your
code will be easier to maintain if you pick the path name from the
current package rather then spelling it out explicitly.

Code:

  String fileName    = "icon.gif";
  String packageName = getClass().getPackage().getName();
  String resource    = "/" + packageName.replace('.','/') + "/" + fileName;
  URL url = ... // continue with the above

And even if you do have images elsewhere, access it via its package
as outlined here because hardcoding paths like "/com/company/..." breaks
down if your code undergo obfuscating, and: it is easier to move code
around without breaking it.

If you do choose to pick resource from a central repository, consider
making a dummy Java class (or interface) which can be used as a package
handle:

  import com.company.images.Images;
  :
  String packageName = Images.class.getPackage().getName();

"Images" should be as simple as this:

  package com.company.images;
  public interface Images{}
Kane Bonnette - 22 Sep 2004 18:29 GMT
...

> Code to access an image via classpath:
>
>   URL url = getClass().getResource ("/com/company/path/icon.gif");
>   ImageIcon icon = new ImageIcon (url);
>   JLabel label = new JLabel (icon);

This worked! thanks for the help. I admit I need to study up on classpaths
more if I plan to continue programming.
Andrew Thompson - 22 Sep 2004 07:35 GMT
> ...
>>
[quoted text clipped - 5 lines]
> This turns out to be the issue. Now the question is, what do I need to do to
> get Java to find my file?

How are you invoking Java?

java -cp . TheMainClass

should add the current directory to the class-path
and the 'getResource' will work.

( But as Paul mentioned, ultimately it is better to jar
your project, that sugestion is simply to allow testing. )

For slightly more on finding resources, check this..
<http://www.physci.org/codes/javafaq.jsp#path>

HTH

Signature

Andrew Thompson
http://www.PhySci.org/codes/  Web & IT Help
http://www.PhySci.org/  Open-source software suite
http://www.1point1C.org/  Science & Technology
http://www.lensescapes.com/  Images that escape the mundane

Ike - 22 Sep 2004 13:43 GMT
I think it's finding the image - I think maybe you didn;t use Andrew's
suggestion exactly as he provided it. Assuming this, my guess is that your
image has not yet loaded when you go to add the JComponent. You need a
MediaTracker. I added a line, and changed a line, in your code as follows:

ImageIcon pic0 = new ImageIcon("pic0.jpg");
if(pic0.getImageLoadStatus() ==  MediaTracker.COMPLETE) ////added
JLabel pic0a = new JLabel(pic0.getImage());        //changed
JPanel panel = new JPanel();
panel.add(pic0a);
frame.getContentPane().add(panel);

//Ike
Kane Bonnette - 22 Sep 2004 18:18 GMT
>I think it's finding the image - I think maybe you didn;t use Andrew's
> suggestion exactly as he provided it. Assuming this, my guess is that your
[quoted text clipped - 9 lines]
>
> //Ike

Thanks for the help, but well....it doesn't work :p  JLabel takes an Icon as
a parameter, not an Image. and it still doesn't display the image. Figured
you'd want to know
Andrew Thompson - 22 Sep 2004 18:55 GMT
> Thanks for the help, but well....it doesn't work :p

..hmmm.  Poking your tongue out at somoene who is trying
to help you ..interesting strategy.

I expect Ike was thinking pretty much along these lines..
<sscce>
import javax.swing.*;
import java.awt.MediaTracker;

public class TestImage {
 public static void main(String[] args) {
   ImageIcon pic0 = new ImageIcon("pic0.jpg");
   JLabel pic0a;
    if(pic0.getImageLoadStatus() ==  MediaTracker.COMPLETE) {
     pic0a = new JLabel(pic0);  
     JPanel panel = new JPanel();
     panel.add(pic0a);
   }
 }
}
</sscce>

..but you need to find that image first, and there
are probably more constructive ways of doing that than
by poking your tongue out at those offering help.

Signature

Andrew Thompson
http://www.PhySci.org/codes/  Web & IT Help
http://www.PhySci.org/  Open-source software suite
http://www.1point1C.org/  Science & Technology
http://www.lensescapes.com/  Images that escape the mundane

Ike - 23 Sep 2004 00:39 GMT
Kate,

Forgive Andrew - he;s an Aussie (and therefore gets bent out of shape too
easily - who can figure those guys out?) Anyhow, Here is a method I use, all
the time. for getting and finding an image, whether on the local disk or in
the resident jar file. If all else fails, go wioth this. It stores multiple
images in a hashtable too, in case you need to call it a subsequent time, it
dont gotta reload - t=dont know how efficient it is but it works nicely for
me //Ike//

example:
I have file day.gif.
I have it in the same directory on the local files system as the app that
contains my method below. I simply call
ImageIcon ii  = new ImageIcon( toImageFromFile("day.gif"));
likewise, if it is in the same directory in a jar file  (i.e both thegraphic
file and the app that contains this method are in teh same 'directory' in
the jar file)

public  Image toImageFromFile(String f){
       if(images==null)
           images=new Hashtable();
       else{
           if (images.containsKey(f)) {
               return (Image)images.get(f);
           }
       }
       Toolkit tk = Toolkit.getDefaultToolkit();
       Image image=null;
       URL url = getClass().getResource(f);
       if(url!=null)
           image = tk.getImage(url);
       else //local, not in jar
           image = tk.getImage(f);
       java.awt.MediaTracker tracker = new java.awt.MediaTracker(this);
       tracker.addImage(image, 0);
       try { tracker.waitForID(0); }
       catch (InterruptedException exception) {}
       catch(Exception e){
           System.out.println("Can't load "+f);
       }
       //if(image!=null)
       //    System.out.println(image);
       images.put(f,image);
       return image;
   }


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.