0

For some reason, I am unable to access an image file while in a package. When I do

JFrame frame = new JFrame();
ImageIcon grass = new ImageIcon("Grass.png");
JLabel lGrass = new JLabel();
lGrass.setIcon(grass);
frame.add(lGrass);

with the files being in the same directory it works, but as soon as I do the same thing in a package, ImageIcon doesn't seem to be able to access Grass.png with no error or image showing up.

  • 1. Use `ImageIO.read` instead of `ImageIcon`, this will generate an error if the image can't be loaded, see [Reading/Loading an Image](https://docs.oracle.com/javase/tutorial/2d/images/loadimage.html) for more details – MadProgrammer May 03 '22 at 21:17
  • 2. The solution will depend on where the image is stored. If the image is embedded in the Jar (how this gets done will depend on the IDE and build system), then you should be using `Class#getResource` to get a `URL` reference to the image. If the image is not within the same package as the class, then you can use `/path/to/image/Grass.png` where `/` represents the root/default package of the project – MadProgrammer May 03 '22 at 21:19
  • 3. `ImageIcon(String)` suggests that the image is a file on the hard drive. In this case, the file MUST be stored in the current working directory, which makes it less then ideal, as the working directory is contextual to the user executing it. Better to use an embedded resource, see point 2, as it allows you greater control – MadProgrammer May 03 '22 at 21:21
  • If that's the case, I'm using VSCode which from what I can tell goes into the current working directory and then executes the main file, so why wouldn't it be able to find the image? – Riley Johnson May 03 '22 at 21:49
  • 1
    Because the "current working" directory is not the same as the directory the class is stored – MadProgrammer May 03 '22 at 21:52
  • 1
    Better to load your files/images as resources: https://technojeeves.com/index.php/aliasjava1/78-loading-files-as-resources-in-java-with-netbeans https://technojeeves.com/index.php/aliasjava1/80-loading-files-as-resources-in-java-with-eclipse – g00se May 04 '22 at 11:47
  • As g00se said, you absolutely want to put your images in a separate directory (e.g. "Images/") and you absolutely want to load the image as a resource, per https://stackoverflow.com/a/31946881/421195 – paulsm4 May 06 '22 at 18:35

0 Answers0