1

I'm making a game and I need to show images for the game to be playable. To make these images show up, I use ImageIO.read and all the images are showing up fine when I run the code in Eclipse. The images that I use are in a separate folder as my main class but I set up this folder as a source folder in the build path.

I've tried to use getClass().getClassLoader().getResource("image.jpg") as well as main.class.getResource("image.jpg"), I've tried to write a /image.jpg instead and for the Runnable Jar file, I've tried to extract the libraries and package the libraries and all these things worked fine in Eclipse but not in the JAR file...

My current code is like this:

File prisonCellFile = new File(main.class.getResource("cellule.jpg").getURI());               

prisonCell = ImageIO.read(prisonCellFile);

Except for the images, everything else works fine in the jar file, and I saw that the images were exported into the jar file, but they are just not showing up... do you know what I did wrong?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An [tag:embedded-resource] must be **accessed by URL** rather than file. Note that `ImageIO` has an overloaded `read` method that will accept an URL. – Andrew Thompson Apr 26 '19 at 16:37
  • 1
    Wow so I just changed File prisonCellFile = new File(main.class.getResource("cellule.jpg").getURI()); into URL prisonCellFile = main.class.getResource(cellule.jpg); and it worked ! Thank you very much, I couldn't imagine that the solution would be so simple haha – Alice Doussin Apr 27 '19 at 15:11
  • You're welcome. Glad you got it sorted. Yes, this is a common problem that is easily fixed (once you know the trick). Now you might enter an answer below (it is not only allowed to answer your own question, but actually encouraged) or simply delete the entire question using the `delete` link under the question. – Andrew Thompson Apr 27 '19 at 15:45

2 Answers2

-1

Thanks to Andrew Thompson's comment, I finally got it to work. I just changed:

 File prisonCellFile = new File(main.class.getResource("cellule.jpg").getURI());

into:

URL prisonCellFile = main.class.getResource("cellule.jpg");
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
-2

You need to use:

File prisonCellFile = new main.class.getResource("cellule.jpg").getFile());

Adrian
  • 1