2

I'm attempting to load an image into a BufferedImage variable and store that in an ArrayList (ArrayList<BufferedImage> imgList).

public void loadImage(){
    try {
        String fileLoc = getClass().getResource("tile_unsearched.jpg").getPath();

        fileLoc = URLDecoder.decode(fileLoc,"UTF-8");

        File aFile = new File(fileLoc);

        img = ImageIO.read(aFile);

        imgList.add(img);
    } catch (IOException e) {
        System.out.println(e);
    } 
} 

However I keep getting this error:

Exception in thread "main" java.lang.NullPointerException
   at MainGameGUI.loadImage(MainGameGUI.java:96)
   at MainGameGUI.<init>(MainGameGUI.java:56)
   at MainDriver.main(MainDriver.java:22)

The path is correct because when I print it, it comes out as /C:/Users/HenBradley/workspace/HH2/bin/sector_a.jpg which is accurate. So I can't imagine my object would be null and given it were, I don't know why it would be, considering the path is correct.

Any clue as to where I'm going wrong?

Also here's the declaration of img and imgList:

private ArrayList<BufferedImage> imgList;
private BufferedImage img = null;
ChewySalmon
  • 576
  • 5
  • 22

1 Answers1

1

imgList is null. Change

private ArrayList<BufferedImage> imgList;

to something like

private List<BufferedImage> imgList = new ArrayList<>();
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249