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?