NullPointerException when accessing image files in a .jar file - java

I have pretty much tried everything but still have this same problem. I have the following setup: I have a images.jar containing a folder called 'images' in which there are multiple image files. I add images.jar to the java build path of the project in eclipse, and i've been trying to use the following code to access the individual images in the jar:
URL url = this.getClass().getResource("images/a.png");
ImageIcon icon = new ImageIcon (url);
Unfortunately, the URL object is always NULL. I don't think this has anything to do with where I put images.jar file as it is added to the classpath in eclipse. I have also tried using the path '/images/a.png', but still the same problem. Any suggestion would be extremely welcome! Thanks.

Try this:
URL url = this.getClass().getClassLoader().getResource("images/a.png");
ImageIcon icon = new ImageIcon(url);
Without getClassLoader() invocation you are only able to access resources in JAR file where the code is stored.

I couldn't reproduce your problem, but my theory is that you are running the class from a different place than you think you are -- that the image and the class are in different jars, or the class is read directly from the class file.

Related

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.

My resource does not load - "Input stream must not be null"

I read ~4 Stackoverflow Posts (1, 2) already, and did everything like it was explained there, but I get a NullPointerException while I try to load an Image.
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Input stream must not be null
My package structure:
Code where I try to load the image:
Image image = new Image(this.getClass().getResourceAsStream("/regexgolf2/ui/img/edit.png"));
I don't understand why It does not work.
Your images are in a package under the src folder. The class loader does not look there for files. The class loader looks for files in your class path.
In order for getResource to work in your case, you need to put the images in the class path.
I suggest you copy the image files manually to your build folder (under the same path, e.g. out/regexgolf2/ui/images and run your app again.
If it works you can start thinking of ways to get the files to the class path (e.g. copy them as part of the build/packaging process or putting them in another folder which is in the class path).
In the case of a netbeans maven javaFX project, the resource (img folder) must be in the resources folder:
Then you can load the resource, for example:
Image escribir = new Image(getClass().getResourceAsStream("/img/login.png"));
I have similar problem in IntelliJ, all look fine but didn't work. In my case, When I rebuild project, all work correct.
I had the same problem in IntelliJ , I wanted to show Image in ImageView on button click and this was a solution for me, don't use getClass().getResourceAsStream("imagePath");
Image image = new Image(String.valueOf(new File("/images/image3.png")));
You can try:
URL url = ClassLoader.getSystemClassLoader().getResource("img/pic.jpg");
Image imProfile = new Image(url.openStream());
ImageView profileImage = new ImageView(imProfile);

null pointer exception even though photo there

I realize this question has been asked in various ways, but I couldn't fix my problem despite this. I'm sure I've done everything correctly and yet it still throws the null pointer exception. Is this a Windows 7 issue with Eclipse?
I'm attaching a screen shot so you can see exactly how I have things laid out and that it isn't working still. I really want to trouble shoot this so I can move on in the tutorial I'm doing. This is so frustrating to be hinged on something so trivial!! My image star.png is located inside the image folder which is in the src folder where the package resides as well. Thank you!
To load an image from within an Eclipse project:
Create a new Source Folder. Do not use a regular folder like the
one already in your workspace.
Create a new package named "star3.images" in the folder you just created.
Copy the images you want (in your case, "star.png") into the package.
Load it using the following:
ImageIcon ii = new ImageIcon(getClass().getResource("images/star.png"));
For all other images, replace "star.png" with the name of whatever image you wish to load.
project; properties; java build path; libraries; add class folder
Add a class folder (called res or something) into the project folder then use:
new ImageIcon(this.getClass().getResource("/res/star.png")).getImage();

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.

Images will not work in a .jar file

When a JAR of an application is created, the images in the application no longer appear. An example of our code for loading images is:
ImageIcon placeHolder = new ImageIcon("src\\Cards\\hidden.png");
We have no idea why this is happening. The application runs as expected if we do not compress it to a JAR; as a JAR, the images simply disappear. We also tried using URLs instead of ImageIcons, but that just causes the program not to run at all.
Any ideas?
EDIT: We are putting the image files into our JAR file in the correct paths, so that's not the problem.
Check the API for the constructor you're calling. The string you pass in is a file path - when the resources are packaged in a JAR, there is no file on the filesystem containing the image, so you can't use this constructor any more.
Instead you'd need to load the resources from a stream, using the classloader, and pull them into a byte array:
byte[] buffer = new byte[IMAGE_MAX_SIZE];
InputStream imageStream = getClassLoader().getResourceAsStream("src\Cards\hidden.png");
imageStream.read(buffer, 0, IMAGE_MAX_SIZE);
ImageIcon placeHolder = new ImageIcon(buffer);
Needs more exception and edge-case handling, of course, but that's the gist of it.
You should load resources from the classpath as such:
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("Cards/hidden.png")
This of course assumes that when you create the JAR, you are actually putting the image files into it.
There is also a method for getting the resource as a URL.
Question: Does the folder src exist in the jar?
Tip: You can open .jar with any unpacking program which supports ZIP to see its contents.
Answer: The way you reference the resource is incorrect, you should do something like getClass().getClassLoader().getResource("Cards/hidden.png") instead.

Categories