-1

I am attempting to make a class which can take a string with an image path and set it as this objects image. I have done it manually before, i.e. creating a new class with an extends main class, but this will get out of hand quickly. Here is the code I have so far:

import java.awt.Image;
import java.net.URL;
import javax.swing.ImageIcon;

public class Sprite {
private int x;
    private int y;
    private ImageIcon ia;
    private URL loc;
    private Image image;

public Sprite(int x, int y) {
    this.x = x;
    this.y = y;
}

public Sprite(int x, int y, String imgLoc) {
    this.x = x;
    this.y = y;

    URL loc = this.getClass().getResource(imgLoc); //problem area is here
    ia = new ImageIcon(loc); //and here
    image = ia.getImage();
    this.setImage(image);
}

When I had a child class, It worked in the child classI put in something like this:

public class Dude extends Sprite {
   public Dude (intx, int y) {
      super(x, y);

      URL loc = this.getClass().getResource("images/dude.png");
      ia = new ImageIcon(loc);
      image = ia.getImage();
      this.setImage(image);
   }
}

But when I try to use the second Sprite Constructor, it gave me an

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(ImageIcon.java:217)
    at Sprite.<init>(Sprite.java:26)

Any suggestions on how to fix this?

OneSurvivor
  • 494
  • 4
  • 15

1 Answers1

0

Okay, I have found the solution. It turns out that I had slightly got the image path wrong, along the lines of:

//Image is called: "images/dude2.png"
//But I called it: "images/dude.png"

I guess the lesson to learn from this is to make absolutely sure everything is called correctly.

OneSurvivor
  • 494
  • 4
  • 15
  • 1
    The `NullPointerException` can be avoided by checking for `null` as well. See also https://stackoverflow.com/a/15581779/3196753. – tresf Oct 04 '17 at 18:06