0

I've been putting all of my images for my Java application in a package called "rtype" inside src where I also also have my Class that deals with these images. I wanted to sort the images and put them in a folder of their own. When I do this, The images will no longer load into the class, and I know it's because I changed the file path. I've done some research and tried a few different things. This is basically what I had originally:

String walkingDown = "WalkingDown.gif";
ImageIcon ii;
Image image;
ii = new ImageIcon(this.getClass().getResource(walkingDown));
image = ii.getImage();

and It worked just fine before I moved the location of the images outside the location of the class. Now it cant find the images. Here is what I tried and found online to try (The folders Name is Sprites):

//use getClassLoader() inbetween to find out where exactly the file is
ii = new ImageIcon(this.getClass().getClassLoader().getResource(standingDown));

and

//Changing the path 
String walkingDown = "src\\Sprites\\WalkingDown.gif";
//also tried a variation of other paths with no luck

I am using the C drive, but don't want to use "C" in my extension, as I want it to be accessible no matter where I put the project. I am fairly stuck at this point and have done enough looking into it to realize that It was time to ask.

Dillon Burton
  • 363
  • 6
  • 16

3 Answers3

1

Your variable is named walkingDown, but you pass in standingDown to the getResource() method.

Joel Christophel
  • 2,604
  • 4
  • 30
  • 49
1

I have a separate "package" for images with that name (in the src folder)

Try something like this:

 try {
        ClassLoader cl = this.getClass().getClassLoader();
        ImageIcon img = new ImageIcon(cl.getResource("images/WalkingDown.gif"));
    }
    catch(Exception imageOops) {
        System.out.println("Could not load program icon.");
        System.out.println(imageOops);
    }
Thorn
  • 4,015
  • 4
  • 23
  • 42
  • 1
    Note that the forward slash / works regardless of operating system (equivalent to windows back slash) – Thorn Dec 03 '12 at 22:05
1
new ImageIcon("src/Sprites/WalkingDown.gif");
irreputable
  • 44,725
  • 9
  • 65
  • 93
  • Ok this works too. But can you tell me what the difference between using this and using the classLoader is?? – Dillon Burton Dec 03 '12 at 22:14
  • 1
    This code is looking for a file in a particular path relative to where the code is being executed from. If you build your project and then run the jar, the above code will not work unless their is a src directory in the same path as the jar file. The method I posted assumes that the image file has been packaged into the jar file so when distributing the app you want to use class loader so that all of your files can be distributed together in one jar. – Thorn Dec 03 '12 at 23:57