AMDG
AMDG

Reputation: 1202

NullPointerException while getting an Image

I am having trouble setting images in my newest game. When I call the method getImage(String), and I get the Image like so:

Image head = getImage("Torso_model_01.png");

I get the following error message:

Err: java.lang.NullPointerException
  At PB2Main.Body(Body.java : 27)
  ...

and so on...

On this tutorial, it explains how to get an image using ImageIcon like so:

String imgFile = "Images/" + img;
URL imgURL = getClass().getClassLoader().getResource(imgFile);
ImageIcon imageIcon;
Image image;
 if(imgURL != null){
  imageIcon = new imageIcon(imgURL);
  image = imageIcon.getImage();
 }

 final Image anImage = image;

I made a method for this:

public URL getURL(String img){
  String imgFile = "Images/" + img;
  URL imgURL = getClass().getClassLoader().getResource(imgFile);
  return imgURL;
}

Then I made a method called getImage(String)

public Image getImage(String img) {
  ImageIcon imageIcon;
  Image image;
  URL imgURL = getClass().getClassLoader().getResource(getURL(img));
  if(imgURL != null){
   imageIcon = new ImageIcon(imgURL);
   image = imageIcon.getImage();
   return image;
  }
   System.err.println("Unable to Locate Image: " + imgURL);
}

Now, I have a class called Body. In that class, I have a constructor:

public Body(float x, float y, String head, String torso){//atm this is just so i can                    get the image to actually draw on the screen
Image Head = debugger.getImage(head);// debugger doubles as a library and debugger
//i also can't have this class extend debugger otherwise it will create a window :/
// is that a glitch or something in Java? :L perhaps i just don't understand
// inheritance very well and what happens exactly when you inherit a class :(
Image Torso = debugger.getImage(torso);

 g2.drawImage(Head, canvas.geWidth()/ 2,canvas.getHeight()/2, null)// canvas: the window to  
 //draw to
 // can someone also quickly explain in their answer what an image observer is please?
 g2.drawImage(Torso, Head.getX() - 5, Head.getY() - 5, null);
}

The compiler gives me the following error message:

java.lang.NullPointerException
At PlazmaBurst2.Body(Body.java: 37)

//the code it brings me to is line 1 in the constructor:
/* null: */ Image Head = debugger.getImage(img);

I don't understand where this NullPointerException is coming from. I did it exactly how they do it in the Custom Graphics Programming section of the same site.

The code works fine if I just copy and paste the code, but not if I use the method getImage(String).

Upvotes: 2

Views: 237

Answers (1)

AMDG
AMDG

Reputation: 1202

You're problem is on line 3 of getImage(String):

URL imgURL = getClass().getClassLoader().getResource(getURL(img));

This should be changed to:

URL imgURL = getURL(img);

Upvotes: 1

Related Questions