Displaying images within a jar file - java

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.

Use Class#getResource to get the URL of your image inside the jar file
enterpriseIcon = new JLabel(new ImageIcon(getClass().getResource("/res/enterprise1.png")));

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();
}
}

I was also facing the same issue till yesterday. I have got a fix for this. Let me share it with you.
In your Eclipse, go to your Project name.
Right your project name.
New -> Source file/folder
Name this Source file/folder as images
Now on your local machine go to the Eclipse workspace where your project
is physically present.
Copy ALL your images into the newly created
'images' folder right there only.
Now go back to Eclipse.
Right click on your Project -> Refresh
Now, wherever you are using images in your .java files , go to those lines and prefix the image location with images/
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. :)

Related

Which is the right way to link images and export in Eclipse (Java)?

The problem I'm having right now has to do with how images are linked when exporting the jar. Right now, my program runs on eclipse and the images do work, but when I try to run it from the exported file, the screen goes white. I have the images in a src/res folder and they appear inside the jar just free in the root directory. the code which I use to link the images is this one:
img = ImageIO.read(Thread.currentThread().getContextClassLoader().getResourceAsStream(
"\\bkg.png"));
My question is, how should I write the path so I can export the jar and get the images to work? Or which line of code should I use to make it work?
Thanks in advance,
Use this :
img = ImageIO.read(MyClass.class.getResourceAsStream(path));
Doing this, you have to know that path is a local path starting from the package of MyClass.

Images not exporting to Jar file

I'm trying to export a Java project to a Jar file but the images are not exporting with it.
This is the code to the image im using
static Icon logo = new ImageIcon("src/images/logo.png");
// LOGO
JLabel imageLogo = new JLabel(logoOne);
imageLogo.setPreferredSize(new Dimension(200, 50));
Ive read you need to factor it into the build path but even after i do that it still doesn't export. Do i need to change my code as well? Or am i factoring it into build path wrong?
Do i need to change my code as well?
Yep. That code is presuming the String to represent a path to a File.
By the time of deployment, it will likely become an embedded-resource.
That being the case, the resource must be accessed by URL instead of File. See the info page for the tag, for a way to form an URL.
Images not exporting to Jar file..
To check for sure, do something like:
jar -tvf the.jar

Image not loading in jar file

I am trying to fix this problem. Trying different solutions but nothing works. I am using NetBeans IDE. I created a project with this structure and files:
E:\java\project\ecadpb\src\ecadpb
The image files are in
E:\java\project\ecadpb\src\
I have specified working folder for my project in Netbeans as E:\java\project\ecadpb
I have created my image icons like this
new ImageIcon("device21.png");
In my source file, it works perfectly while running the project in Netbeans but images are not showing up when I build and run my JAR file separately. But the image files are inside the JAR.
I have also tried the answers for the same question asked previously.
URL imageUrl=getClass().getResource("device21.png");
new ImageIcon(imageUrl);
But it doesn't work in my case. I am building a JAR file for the first time. Can anyone help me with this!!
A simple way of doing this will be to add the image in your classpath or a directory in your classpath say img as shown below:
E:\java\project\ecadpb\src\main\java\img\device21.png
And then load your image from this location like this:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource("img/device21.png");
ImageIcon icon = new ImageIcon(resource);
Create a source folder called Images (ie if you're using eclipse, right-click your project -> new ->sourceFolder). Call it whatever you want, i called my Images. Put some images in it.
Now i had JLabels where i gave them ImageIcons. Look at the following code.
ImageIcon BPawn;
ImageIcon WPawn;
JLabel Label = new JLabel[8][8] //2D array of labels that gives each spot a position.
public void setPieces(){
//set up pawns in their respective positions.
BPawn = new ImageIcon("Images/BPawn.png", "BPawn");
WPawn = new ImageIcon("Images/WPawn.png", "WPawn");
for(int i=0;i<Label[0].length;i++){
Label[1][i].setIcon(BPawn);
Label[6][i].setIcon(WPawn);
}//end for
}//end setPieces.
There is a lot more in setPieces() method, but this glimpse is how you would reference the images in your source folder when you create an executable jar and want the images to show up.
I think answer could be one these suggestions here
I have used a similar approach,
a) Specify the package path to the image file name.
b) Make sure that the image file is not ommited by your build scripts and that it is present in your jar file.

Simple ImageIcon issue

I can't get icons to appear on my button. I've copied this code from a book as I'm a beginner trying to grasp Java programming. Unfortunately I can't progress without getting this working, the other exercises are based on GUI images. I believe I've followed the exact steps, hopefully somebody can help!
Here is the simple code:
package Chapter13;
import javax.swing.*;
/** #author Chris */
public class TestButtonIcons extends JFrame
{
public static void main(String[] args)
{
JFrame frame = new TestButtonIcons();
frame.setTitle("ButtonIcons");
frame.setSize(200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public TestButtonIcons()
{
ImageIcon usIcon = new ImageIcon("image/usIcon.gif");
ImageIcon caIcon = new ImageIcon("image/caIcon.gif");
ImageIcon ukIcon = new ImageIcon("image/ukIcon.gif");
JButton jbt = new JButton("Click it", usIcon);
jbt.setPressedIcon(caIcon);
jbt.setRolloverIcon(ukIcon);
getContentPane().add(jbt);
}
}
File Hierachy:
As you can see I've copied the "image" file twice as an attempt to try and debug this. All the images are in the "image" folder despite the photos not showing them all.
you need to create the image folder outside of the source package when you run from the netbeans while when you run directly executing the jar then you need to put the executable jar file and image folder in same folder or same place
It seems a bit of a problem with BookExcercises; that is not a normal project.
A normal NetBeans project (you can see all in the Files tab to the right of the Projects tab): there is a src directory shown under Source Packages. Building a project fills a target directory. Now a build would put the .class files there and also copy your images. Run (project) would run with as class path the target directory. Run File however might not find the images in the target directory.
A solution depends on the BookExcercises project. You might create a new project for every excercise. Depends.
If you are using a command Prompt to run your program, then simply paste this image folder alongside your chapter13 package folder(which contains your TestButtonIcons.class).
Or if you using some IDE, check where your compiled stuff goes. Again paste your image folder alongside your chapter13 package folder (which contains your TestButtonIcons.class). That will do the needful to run the program as you are expecting.
Regards

Set Icon Image in Jar file

The following code works fine when running on NetBeans.
this.getFrame().setIconImage(Toolkit.getDefaultToolkit().getImage("PlagiaLyzerIcon.png"));
However, once it was built into Jar file, the icon was gone.
Anyone has idea what's the problem? I realized I've to put the icon image on the root directory, however, after compiling into JAR, the icon gone.
Thanks for any help ...
Hi everyone, the problem was solved with the following code,
this.getFrame().setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("plagialyzer/resources/PlagiaLyzerIcon.png")));
It works once compiled into jar file.
Use
this.getFrame().setIconImage(
new imageIcon(getClass().getClassLoader().getResource("PlagiaLyzerIcon.png"))
);
instead.
Note:
this line only works if the images are in the root of the jar file. If not, you have to specify the folder on the string:
getResource("yourfolder/PlagiaLyzerIcon.png")
That is because the Netbeans IDE has a different classpath, than when running the jar-file stand-alone (without Ant).
Assume your Netbeans project is at location /project/:
The classpath is: /project/build/classes/ and the project root /project/. If your icons are stored in: /project/myicons/, then they are part of the classpath, since /project/ is too. But when you build your project, only files in /project/build/classes/ will eventually end up in the jar-file, these files are "build" from /projcet/src/.
Solution:
Move your icons into a source-package: /project/src/myicons/
Or, add the /project/myicons/ folder to your sources (right-click your project -> Properties -> Sources -> add your folder there)
Thanks a lot...
Here the code that works for me!!!!
BufferedImage image = null;
try {
image = ImageIO.read(getClass().getClassLoader().getResource("images/frame.png"));
} catch (IOException e) {
e.printStackTrace();
}
super.setIconImage(image);
Did you specify the build path to your icons in the options of Netbean before exporting the JAR? On Eclipse it's done by adding a source folder inside the Java Build Path as shown in this screenshot. Should be the same way on Netbeans?
Using NetBeans like myself, just put the logo (in my case mylogo.png) inside src/ directory in your project folder. Make sure size is 32 x 32 pixel to ensure best quality for icon. I couldn't manage to set .ico images as my JFrame icon but .png worked well.
By extending JFrame, I directly set my jar icon with:
Image getIcon()
{ return Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("mylogo.png")); }
setIconImage(getIcon());
After clean and build jar, the jar file icon still isn't changed (still the jar default icon) but when you execute the jar file the icon in title bar and taskbar will be your custom icon. You can change the jar file icon by creating shortcuts and change icon for that shortcut. Best resolution for shortcut icon is 512 x 512 pixel .ico
I use this code, but it only changes the little icon that you have top left on your windows and the icon that you have at the button on the bar where you can see which app is open.
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
constuctor of my class extends JFrame{
BufferedImage image = null;
try {
image = ImageIO.read(new File("path/logo.png"));
} catch (IOException e) {
e.printStackTrace();
}
super.setIconImage(image);
}

Categories