Reputation: 1
I've been trying to add Images to my jar file for some time now I've searched many ways but nothing works. Many threads say various methods that don't work and its frustrating me.
I have the problem where when I run it with Intellij the images render well, but when I build it into a .jar file all the images don't render
My normal code is written like this:
> randomIcon = new ImageIcon("src/"+ randomChoice + ".png");
I've tried to do this but it returns as a Exception in thread "main" java.lang.NullPointerException
randomIcon = new ImageIcon(getClass().getResourceAsStream("src/" + randomChoice + ".png").toString());
I'm not sure what I'm doing, I'm just very confused
This is my project folder
I'd be very happy if someone says a simple solution or tell me what I'm doing wrong! Thank you!
Upvotes: 0
Views: 439
Reputation: 965
The location of resources is not correct. It should be under the /src/main/resources
Then you can use following to read the file.
InputStream is = getClass().getClassLoader().getResourceAsStream("file.txt");
InputStream is = JavaClassName.class.getClassLoader().getResourceAsStream("file.txt");
Reference : https://mkyong.com/java/java-read-a-file-from-resources-folder/ https://docs.oracle.com/javase/8/docs/technotes/guides/lang/resources.html
Upvotes: 2