views:

241

answers:

1

Hello,

I am trying to load an image file (gif) which is stored locally in the same directory as my Eclipse java project:

ref is the relative path where the gif image is stored.

public Sprite getSprite(String ref) {
      BufferedImage sourceImage = null;
      try {
        URL url = this.getClass().getClassLoader().getResource(ref);     
        if (url == null) {
        fail("Can't find ref: "+ref);
       }
       sourceImage = ImageIO.read(url);
       } catch (IOException e) {
     fail("Failed to load: "+ref);
       }
}

The client code that uses the above method is:

public Entity(String ref,int x,int y) {
     this.sprite = ResourceManager.getSprite("sprites/alien.gif");
     this.x = x;
     this.y = y;
    }

In the Eclipse workspace and within my project directory I have a folder spriteswith the gif images stored there. But the client code always returns: Can't find ref: sprites/ship.gif

Am I doing something wrong in my approach above to load the gif image? Is there a better more straightforward way to do a file lookup in this case?

Many thanks for any advice.

+3  A: 

The getResource() method searches your classpath to find the file, likely the sprites directory is not in your classpath.

Try open your project properties -> Java Build Path, select Libraries tab and click on Add Class Folder button then select the parent directory of sprites.

DJ
I think you mean the parent directory of the sprites directory, don't you?
Benjamin Cox
Yes, that did the trick actually! The parent directory that is
denchr
you are right, I fixed the answer to point to parent directory
DJ
You have no idea how long I've looked for this answer.Thx!
Tawani