Reputation: 107
My intellij can't find local .png images.
private String craft = "craft.png";
ImageIcon ii = new ImageIcon(this.getClass().getResource(craft));
The .png is located in the same directory as the java files. I don't understand why it isn't working. Using maven build, tried alternating from resources to java, but still no luck :(
Upvotes: 1
Views: 5190
Reputation: 839
tried alternating from resources to java
So at first you tried putting craft.png into src/main/resources
. That is where it must be put according to Maven (not in src/main/java).
But it didn't work because
this.getClass().getResource("craft.png")
tries to find "craft.png" relative to the this.class's package. If your this.class is in package foo.bar then you must put craft.png in src/main/resources/foo/bar/
You can also provide an absolute path in getResource() by using a leading slash /
. For example put craft.png into a custom folder under resources src/main/resources/customFolder/
and read it with the leading slash /
in front of customFolder:
this.getClass().getResource("/customFolder/craft.png")
If you don't use leading slash in getResource()
method then internally class's package name is prepended to the resource name to make it absolute.
This behavior is explained in Class.getResource()
Upvotes: 1
Reputation: 402543
craft.png
must be placed into src/main/resources
, otherwise it will be not copied to the classpath according to the Maven rules. See this answer for more details.
Your code should be also changed to:
private String craft = "/craft.png";
Here is the sample working project.
Upvotes: 4
Reputation: 8919
Go to your IntelliJ Preferences and search for "resource patterns" (or just go straight to the "Compiler" settings).
IntelliJ will only copy certain resources to the output directory. Make sure the resource pattern includes *.png.
I have my resource pattern set to !*.java (copy everything that's not a source file) which seems to work fine (and should really be the default, in my opinion).
Upvotes: 1