I see other StackOverflow users have been having this error. However, when I try what the first person did (make it use getClass().getClassLoader().getResource(myPath)
, which is URL), it doesn't work in the Eclipse IDE run nor in the JAR file. I can't make sense of one of the answers on here, but I do understand this one:
The getImage call is looking in the file system working directory, not inside the Jar file. This is why the jar file loads the images successfully when they are placed in the same directory outside the jar file. If the images are bundled in the jar file, they are no longer file system files to be accessed, but rather Jar file resources. There is a different way to load these, but sorry, I don't know it off the top of my head
Before this, I thought the image file (whose relative path is /images/folder.jpg
wasn't being included in the JAR file. I extracted it and could not find the image.) In attempt to address that, I included images
folder in build path (Project > Properties > Java build path > Source
). After doing so, I extract JAR file again, and notice the picture is there, but not in images folder.
This is what I tried from the Java code side:
//this.selectDirector = new JButton(new ImageIcon(getClass().getClassLoader().getResource("images/folder.jpg")));
this.selectDirectory = new JButton(new ImageIcon("images/folder.jpg"));
Is there answer to this (or way to do what the quote says should be done)? UPDATE:
I moved images
folder to inside bin
folder, and removed it from the build path (so that only src
folder was on the build path). For good measure, I also placed it in the src
folder. I updated my two lines of code to:
this.selectDirector = new JButton(new ImageIcon(getClass().getClassLoader().getResource("images/folder.jpg")));
//this.selectDirectory = new JButton(new ImageIcon("src/images/folder.jpg"));
Now, it works from Eclipse, but still doesn't work from JAR file (it's throwing NullPointerException
).