Reputation: 3866
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
).
Upvotes: 1
Views: 1708
Reputation: 3866
I could not figure out how to guarantee Eclipse shipping the images
folder with folder.jpg
in it, with the rest of the code, even if I put it in src
and bin
folders. Despite that, I was still able to fix the problem
What I ended up doing
I remembered what JAR file was: a Java-generated compressed file (similar to a RAR file or a ZIP file). Knowing that, I opened up generated JAR file with WinRAR, went to project directory, and dragged images
folder to WinRAR instance. WinRAR put the images
folder in the JAR file! I then change my Java code (that uses folder.jpg
) to: this.selectDirectory = new JButton(new ImageIcon(getClass().getClassLoader().getResource("images/folder.jpg")));
The downside
The downside is that I will have to keep images
folder floating around, so that I run WinRAR and copy images
over, on every new export from Eclipse. There must exist better way, but I will accept this one, for now...
Upvotes: 0