Reputation: 2436
I am trying to set Image to a JLabel. I used this code, And it works fine in the IDE. But when I try to run Executable Jar file in dist folder It gives me this error.
javax.imageio.IIOException: Can't read input file!
How to fix that issue. Please anyone can help me? Thanks in advance.
Code is,
ImageIcon iconPicture = new ImageIcon(ImageIO.read(new File("./src/PIC/Images/profileImage.png")));
pictureLabel.setIcon(iconPicture);
Upvotes: 1
Views: 1095
Reputation: 347204
You can't rely on the "working directory" been the same as the location where the Jar/classes are stored.
ImageIcon iconPicture = new ImageIcon(ImageIO.read(new File("./src/PIC/Images/profileImage.png")));
This suggests to me that you are dealing with an embedded resource, one which is contained within the classpath/Jar file. In this case, you should be loading the resource using Class#getResource
instead, as the resource won't be readable as a File
(if it's contained in the Jar file).
So, instead of the above, you should be doing something more like...
ImageIcon iconPicture = new ImageIcon(ImageIO.read(getClass().getResource("/PIC/Images/profileImage.png")));
Upvotes: 4
Reputation: 18357
Your program when run is not able to find image from your given path
./src/PIC/Images/profileImage.png
Here . refers to current directory and when you must be running your program, . must not be what you intend it to be. So one way to fix the problem is to either use absolute path, which would be something like
D:/work/proj1/src/PIC/Images/profileImage.png
Or
You need to find the current dir as per your project and then construct the correct relative path.
You can find current dir path with following one liner code,
System.out.println(new File(".").getCanonicalPath());
Find your current path and then correct the relative path of image that you have given.
Upvotes: 2