Reputation: 5322
I am trying to display an icon in my GUI by using a relative path, as in "display image from resources/image.png
". I have tried a million different ways to express this, but nothing works. This makes me think it's a problem with my IntelliJ IDEA settings or project structure. I have set up the "resources" folder as a "resources folder". I don't know what else it expects me to do.
How can I load an icon from a file using a relative path in a Java project within IntelliJ IDEA?
My project structure:
src/main/java/ <-- set as "sources" in IntelliJ
src/main/java/ui/ <-- contains classes for my GUI
src/main/resources/ <-- set as "resources" in IntelliJ. Contains images.
Edit: Able to use relative path to confirm that file is found, not able to load it as icon.
String path = "src/main/resources/image.png";
System.out.println(new File(path).exists()); <-- true
Upvotes: 1
Views: 6931
Reputation: 12367
Resources are on classpath, not on filesystem path - which is taken relative from running directory, which is project directory when you are running it from idea. Usually you will distribute your aplication as jar, and this it is better to load resources from classpath. In zour case - from root directory
Upvotes: 0
Reputation: 2849
I've encountered this issue many times and what worked for me was using InputStream
InputStream is = Main.class.getClassLoader().getResourceAsStream("name_of_file.png");
Using InputStream
will allow you read from various file types. Now to load in the icon you can do
Icon icon = new ImageIcon(ImageIO.read(is));
Upvotes: 1