Reputation: 767
I know this question has been asked before, but I have gone over all the solutions I could find and cannot make any of them work for me. I have a program in Eclipse that I am trying to export to an executable jar file. It is the first time I have done this. When I execute the jar, my program images do not show up. So I did some research and found I need to load them as resources, but I cannot seem to make it work.
Here is the code I was using to load the images without the jar:
private void initComponents()
{
// create an enterprise icon and make it invisible
enterpriseIcon = new JLabel(new ImageIcon("res/enterprise1.png"));
enterpriseIcon.setVisible(false);
}
I have all my images in a folder named res in my root project directory, and I told Eclipse to put this folder in the build path.
When the images wouldn't show up when running the jar file, I tried the following:
enterpriseIcon = new JLabel(new ImageIcon(getClass().getResource("/res/enterprise1.png")));
and
enterpriseIcon = new JLabel(new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/res/enterprise.png"))));
However, when either of these is run from within Eclipse, I get a null pointer exception. (I tried a few other things as well, but the above were the only solutions I thought I understood.)
Any help getting this to work would be appreciated.
Upvotes: 0
Views: 650
Reputation: 27
I was also facing the same issue till yesterday. I have got a fix for this. Let me share it with you.
Example : XXX xxx = XXXX (example.jpg) Change it with .... XXX xxx = XXXX (images/example.jpg)
BOOM !! The images will be shown when you run the .jar file.
NOTE : Do not run the .jar file from cmd using java -jar AppName.jar Instead, just double click the .jar file and you will be seeing the images.
If it works for you, kindly upvote. :)
Upvotes: 0
Reputation: 1
Try this. This works well for me :)
private void initComponents() {
try {
BufferedImage icon = ImageIO.read(getClass().getResource("/enterprise1.png"));
frame.setIconImage(icon);
} catch (IOException e) {
e.printStackTrace();
}
}
Upvotes: 0
Reputation: 19506
Use Class#getResource
to get the URL of your image inside the jar file
enterpriseIcon = new JLabel(new ImageIcon(getClass().getResource("/res/enterprise1.png")));
Upvotes: 1