I am developing a java project in eclipse. To distribute the program, I created an executable .jar file through the export function in eclipse.
My program will load several images, which are stored in a folder called "tableImages". I upload images through ClassLoader (below you will find code snippets). The problem is this: when executing a program from a .jar file, it throws a NullPointerException when loading one of the .png files in the above folder. The funny thing is that some of the .png files in the same folder load correctly, that is, they do not throw a NullPointerException.
I checked the contents of .jar using the jar tf command. The image, which apparently could not be uploaded, was packed in a jar. So what causes this NullPointerException and how can I solve it?
Here is a class with which I draw images in a frame.
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import java.net.*;
public class LoadBackgroundImage extends Component {
private static final long serialVersionUID = 1L;
BufferedImage img;
public void paint(Graphics g){
g.drawImage(img, 0, 0, null);
}
public LoadBackgroundImage(String image){
URL url = ClassLoader.getSystemResource(image);
try{
img = ImageIO.read(url);
this.setSize(img.getWidth(), img.getHeight());
}catch(IOException e){
System.err.println(e.getMessage());
}
}
public Dimension getPreferredSize(){
if(img == null){
return new Dimension(100, 100);
}else{
return new Dimension(img.getWidth(null), img.getHeight(null));
}
}
public BufferedImage getImage(){
return img;
}
}
Many thanks for your help!
source
share