0

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.

denchr
  • 4,142
  • 13
  • 48
  • 51
  • this has nothing to do with the question you ask, but technically, an Sprite is a Object with position, texture, etc etc, and that you are trying to load in here is a "Texture" instead of a Sprite , is just for your knowledge – Jose De Gouveia Mar 14 '13 at 10:22

1 Answers1

3

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.
  • 6,664
  • 1
  • 33
  • 48