Java images not appearing in JAR file [duplicate] - java

This question already has answers here:
Java Swing: Displaying images from within a Jar
(5 answers)
Closed 9 years ago.
Heres how i call the image
Icon logoOne = new ImageIcon("logo.png");
// LOGO
JLabel imageLogo = new JLabel(logoOne);
imageLogo.setPreferredSize(new Dimension(200, 50));
Its just added to a panel in a JFrame and works fine when running in eclipse but doesnt show up when exported to JAR.
can anyone help ?

When exporting your JAR file, you've to make sure you're also including the image files in your JAR file. For example: If you have a folder called 'res' containing the images, you have to check the checkbox before this folder in order to make sure this folder, and the images are being included.
You might want to add some trouble shooting code. For example: Add some code that prints in the console if this image file exists. Export your JAR file, run your JAR via the console/terminal and check the result. If this shows you the image doesn't exists, you know it's a problem with your exported JAR file.
You might want to try reaching the image as a resource steam, give the following code sample a try:
java.net.URL logoOneUrl = getClass().getResource("logo.png");
Icon logoOne = new ImageIcon(logoOneUrl );

When you call
Icon logoOne = new ImageIcon("logo.png");
You are reading the image from a file (see javadoc). When you export to the jar, this file is no longer available, so you need to use ClassLoader#getResourceFromClasspath() or use one of the other constructors.

That depends on how you added the Image to the jar file.
In the normal case, the image lies in one of your source folders, and eclipse takes care of exporting it into the Jar file. If that is the case, you can load the via the ClassLoader. there are several methods for that. I mostly use this.getClass().getResourceAsStream("logo.png"). If you only use the standard Classloader (which would be the normal case) this will work.

Don't get your image as a file as you're currently doing so. Instead get it as a resource. If you search this site, you'll find similar questions about occurring 2-4 times per week.
i.e.,
String imageResource = //.... string to image resource path
Image myImage = ImageIO.read(getClass().getResourceAsStream(imageResource));
Icon logo = new ImageIcon(myImage);
Note that the imageResource String is the String that represents the resource path to your image. This will depend on where your image is held in the jar file and where it is relative to the class files, information that we don't know at the moment.

Related

Can I have my entire application in a single JAR file?

I don't quite understand how creation of a Swing application really works.
I have created a simple application that gets a background image from a path.
ImageIcon imageIcon = new ImageIcon("C:\\Java\\ApplicationName\\out\\Resourses\\backGround.jpg");
Image image = imageIcon.getImage(); // Создание картинки из него
Image temp = image.getScaledInstance(500,500,Image.SCALE_SMOOTH);
imageIcon = new ImageIcon(temp);
g2d.drawImage(temp,0,0,null);
It works, so I decided to make a JAR file independent from changes in the Java folder (like deleting this image) and put images in src - images ( package ). I don't know if it is possible though.
I started to get background image like this.
ImageIcon imageIcon = new ImageIcon(this.getClass().getResource("/images/backGround.jpg"));
The program works perfectly in IntelliJ IDEA but if I extract it to JAR file I get a blank background screen. Why is that?
And can I have my entire application including images in a single JAR file? One that is not dependent on other folders?
You can certainly put the image and the code in a single jar file. The image is not loading either because it's not in the jar file, or because it's not at the path /images/backGround.jpg inside the jar.
One helpful thing about jar files that you may not know: they are in .zip format, so you can use any zip tool to see what is inside the jar (temporarily renaming the jar file to .zip might make this easier). IF the image is not there, fix your jar build (you didn't say how you are making it, so not sure what you need to change). If the image is there but under a different path, then fix the jar build to put it in the right place, or change the path you are reading it from.
Yes definitely you can include your entire application into single jar file i.e. Runnable jar file. But i would suggest you not to include your image inside the jar file, instead pass that image path to an Property file and use that property file in your code for image path. So that even if next time you need to change the image you just change the path in your property file and you dont have to export your entire project again.

JAVA SWT Can't get the image relative path

I'm stuck again on a problem concerning SWT using Java RCP.
What I want :
I have a Composite in which I wanna load an Image in it.
How it's currently done :
For this, I use a SWT Label, and call the method setImage(image).
The image (img.jpg) is found in a directory called /img/ next to the /src/ one. The directory is added in the Build Path. Here's a screen to illustrate :
directories
I call this image as follows :
InputStream is = getClass().getClassLoader().getResourceAsStream("/img/img.jpg");
ImageData imageData = new ImageData(is);
Label label = new Label(picRoom, SWT.NONE);
label.setImage(new Image(display, imageData));
What's the problem ? :
Once again, when I launch the project, everything goes right. The image loads and displays perfectly. But when I export it, the image doesn't anymore. The problem comes from the path actually. When I make an image as new Image(display, absolutePathToTheImage), it loads even if exported. But I want the image in the /img/ directory, because if I launch the project from the .exe from another computer, I want it to have the picture, wherever it is (so in /img/).
I've tried many solutions across the internet (using URL in particular), but no one worked. And as I said, I need the image to be in the /img/ directory and to take the relative path. And, of course, to work after exporting the project as a .exe .
Thanks in advance.
Kosnyru.
First make sure your img directory is included in the build.properties includes so that it is included in the exported plugin.
Then use the FileLocator class to find the image using a relative path:
// Your plugin's bundle - there are several ways to get this
Bundle bundle = FrameworkUtil.getBundle(getClass());
// Relative path in the plugin
String path = "/img/img.jpg";
URL url = FileLocator.find(bundle, new Path(path), null);
ImageDescriptor imageDesc = ImageDescriptor.createFromURL(url);
Image image = imageDesc.createImage();
Assuming your file is in resources directory, you can do something like:
JLabel label = new JLabel(new ImageIcon(this.getClass().getResource("/logo.png")));

images not showing up when running JAR

I've spend 5 hours already and have no idea why images are not loaded when running Jar.
Project structure:
Blackjack_Game
- Source Packages
- Images
- blackjack
.... classes...
At project properties I have src - Source Packages folder added by default. Tried to put images directly into the project's folder and removing /Images/, but still no help.
Inside the code I have:
dealer_url = getClass().getResource("/Images/4_of_hearts.jpg");
File img = new File(dealerCardGenerator.dealer_url.getPath());
BufferedImage bufferedImage = ImageIO.read(img);
dealerCardGenerator.imageIcon = new ImageIcon(bufferedImage);
So inside NetBeans IDE everything is OK. Fully working. But after built&clean I see no images, but all actions are done.
Can you please suggest what is wrong? Getting so mad because of this ((((
A jar entry is not a file. java.io.File can only identify a file, not a jar entry. java.net.URL however can identify a jar entry using the jar: scheme, or a file using the file: scheme. That's why Class.getResource() returns a URL not a File.
Two solutions:
use the URL: ImageIO.read(getClass().getResource("whatever"))
ImageIO can also use an already-opened stream, which classloader can provide:
ImageIO.read(getClass().getResourceAsStream("whatever"))
Duplicate of at least #2-4 of the questions autosuggested as related:
Including Images with an executable jar
Loading images in a jar
Getting images from a .jar file
Thank you all for clarifying the problem. I've realized why some functions were not working.
So the solution is to replace URL with ImageIcon:
ImageIcon i2 = new javax.swing.ImageIcon(getClass().getResource("whatever"));
and then just set icon as label icon:
jLabel1.setIcon(i2);
In this way JAR works. Previously, all methods after this icon set operation were not working, as the program was actually stopped, now everything works fine.

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.

Categories