I am having a issues with running a runnable jar file which has a image icon in it.
Code runs on eclipse nicely and displays the icon in a JFrame
. The way I add it is by adding it to a JLabel
and then adding that JLabel
to the JFrame
. I export the project into a runnable Jar file and when I double click the jar. It doesn't run.
I tested out just adding a normal JLabel
onto the JFrame
without the icon code and it works when I exported and ran it.
Whenever I add the following line to code, it messes the runnable Jar File.
JLabel s1 = new JLabel(new ImageIcon(getClass().getResource("/Images/Pattern1.png")));
I noticed it could be something wrong when it gets the resources. My Image Pattern1, is stored in a folder called Images and that folder is inside my project src folder. So I am sure it's in the runnable jar file when I export it.
Here my code
package main;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MyFrame extends JFrame {
public MyFrame() {
JLabel s1 = new JLabel(new ImageIcon(getClass().getResource("/Images/Pattern1.png")));
this.add(s1);
//JLabel test = new JLabel("Test");
//this.add(test);
}
public static void main(String[] args) {
MyFrame f = new MyFrame();
f.pack();
f.setVisible(true);
}
}
This is what my files in my project looks like.
Thanks
Especially on Windows, Java can be a lenient on the use of case within the file names. When running in Eclipse, the Pattern1.PNG
is probably been picked up off the file system directly.
Once embedded within the Jar however, the case matching becomes EXACT. This is because the resource is simply added to a zip file and Java uses the Zip Entry information to find content.
Make sure you naming is EXACT to avoid issues. Try /Images/Pattern1.PNG
instead of /Images/Pattern1.png