So I was attempting to upload some images to a buffered image array in a class, but when I run the code, the class that I have the code in returns an npe. The image is a png file. Here's the code:
...
private BufferedImage[] img = new BufferedImage[2];
public Backdrop(String args[]) {
for (int i = 1; i <= 2; i++) {
String path = "resources/Map1"+i+".png";
File file = new File(path);
if (file.length() <= 0 || !file.isFile() || !file.exists()) {
System.out.println("Image " + i + " failed first test");
}
try {
FileInputStream fis = new FileInputStream(file);
img[i-1] = ImageIO.read(fis);
} catch (IOException e) {
e.printStackTrace();
}
if (img[i-1] == null) {
System.out.println("Failed to upload Map1" + i + ".png to array");
}
}
}
public void render(Graphics g){
switch(currentBackdrop) {
case Map11:
/*//upload map image
g.drawImage(img, 0, 0, null);*/
break;
case Menu:
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
break;
default:
break;
}
}
As the title says, I've already tried using a fileinputstream, a imageinputstream, a bufferedinputstream. I've also tried using new File(...). Same thing happens. I'm thinking it's the img[i-1] = ImageIO.read(fis); because when I comment it out everything works fine (obviously the image doesn't display because I've commented the g.drawImage code out and the array is empty). Before anything is said about the fact that there's only a small number inside the for loop thing, I am going to increase it later on, I'm just trying to get this to work first. I'm pretty sure the path is in the correct location because if I change the path to something like fdilsjah.png, the error would be a filenotfoundexception. Also, the first println code doesn't run, so I think that also shows that file exists.
Here's the error messages:
Exception in thread "Thread-0" java.lang.NullPointerException
at com.CASGame.InsomniacCheese.Game.render(Game.java:137)
at com.CASGame.InsomniacCheese.Game.run(Game.java:85)
so Game.java:137 is just backdrop.render(g) (which is just a private instance of the Backdrop class)