I have searched Google, SE, and Oracle's documentation for information on how to do this, but I can't seem to make it work.
I have found several posts regarding whether to use getResource()
or getResourceAsStream()
and how to format the file name, but none that I can apply to my situation.
My directory structure looks like this (with some extra levels in the resource folder):
Root Folder
|
|_____ bin (compiled .class files go here)
|
|_____ src
| |
| |_____ packageA
| | |
| | |_____ packageAa
| | |
| | |_____ images.java
| | |
| | |_____ resources
| | |
| | |_____ icon1.gif
| |
| |_____ packageB
| |
| ... (More packages with sub-packages)
|
|_____ resources (should it go here?)
|
|_____ icon2.gif
In my actual program I have 107 gif images with file names that can be derived from object values. These images are currently located in both resource folders because I have been playing around with both to try to get one to work.
My current code tries this:
String imageFileName = getFileName(obj); // returns a string such as "/resources/cardImages/acespades.gif"
URL imageURL = getClass().getClassLoader().getResource(imageFileName);
ImageIcon icon = new ImageIcon(imageURL);
I keep getting a null pointer exception regardless of leading backslashes.
How should I format the file name and or create a URL object to get the images?
Note: I am using Sublime Text 3 with Javatar to compile my code. The folder structure (the bin folder) is created by Javatar. My "Source folder" is set to src
and the "root folder" shown above is my flash drive.
====================================================
Edit:
I tried Peter's suggestions and these are the results:
URL imageURL = getClass().getResource("resources/cardImages/back1.gif");
System.out.println(imageURL);
ImageIcon icon = new ImageIcon("resources/cardImages/back1.gif");
The println statement prints out null, but the ImageIcon does correctly display the image. I understand it this loads the image from the folder next to the .java file.
URL imageURL = getClass().getResource("/resources/cardImages/back1.gif");
System.out.println(imageURL);
ImageIcon icon = new ImageIcon("/resources/cardImages/back1.gif");
The println still prints null, but now the image is not displayed. I copied and pasted the entire resource folder to make sure it was identical in both locations.