0

I'm trying to load several images into an array. But for some reason, I get a NullPointerExeption when trying to do the actual loading (ImageIO.read()). I can't see whats wrong, probably from fiddeling around with it too much that I got blind for the mistake. This is the loop that tries to load the images:

for (int i = 0; i <= 1; i++) {
        try {
            image[i] = ImageIO.read(new File(String.format("TDs/TD%d.png", i)));
            bg[i] = ImageIO.read(new File(String.format("BGs/BG%d.png", i)));
        } catch (IOException e) {
        }
    }

I currently have only two images to switch between, but I'll change that soon.

The painting happens using

g2d.drawImage(bg[1], 0, 0, null);

Both variables are initialized by

Image[] image, bg;

And last but not least proof that all images are actually there is found

here

Thanks for helping a stupid person.


EDIT: Thank you alot for the answers, as initiaizing the array this way works! I feel like an idiot now since I looked at all other array inits to find that they were initialized exactly the same way as you told me... Sorry for stealing your time!

PS: No need to handle IOExeptions since these are textures for a game - they don't change and you can't / shouldn't change them either. I will add a Messagebox with a message in case someone decides to mess around anyways.

mindoverflow
  • 364
  • 1
  • 12

2 Answers2

1

You need to create a new array. You only declare the array like so:

Image[] image;

But to store elements in your array you have to initialize it like so:

Image[] image = new Image[2] // value count

For your example you could try this

int imageCount = 2;
Image[] image = new Image[imageCount];
for (int i = 0; i < imageCount; i++) {
    try {
        image[i] = ImageIO.read(new File(String.format("TDs/TD%d.png", i)));
        bg[i] = ImageIO.read(new File(String.format("BGs/BG%d.png", i)));
    } catch (IOException e) {
    }
}

Or as an alternative, if you don't know how many values you want to store. You could use an ArrayList. Like so:

ArrayList<Image> images = new ArrayList<>();

//add image
images.add(ImageIO.read(new File(String.format("TDs/TD%d.png", i))));
Leon Husmann
  • 664
  • 1
  • 6
  • 25
0

When you are initializing an array of images, you might want to try to do something like this:

Image[] image = new Image[2]; //or replace 2 by the amount of images you will be loading.
Image[] bg = new Image[2]; //same for this one.

This way the array is initialized properly.

N00b Pr0grammer
  • 4,503
  • 5
  • 32
  • 46