Reputation: 477
I'm trying to do this example http://zetcode.com/tutorials/javagamestutorial/movingsprites/ but i get these errors
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at rtype.Craft.<init>(Craft.java:19)
at rtype.board.<init>(board.java:28)
at rtype.Rtype.<init>(Rtype.java:9)
at rtype.Rtype.main(Rtype.java:20)
I have tried putting my image in various places inside my project file and even writing the absolute path.
What do i do wrong? I use eclipse.
edit: Excuse me here's the code
private String craft = "craft.png";
private int dx;
private int dy;
private int x;
private int y;
private Image image;
public Craft() {
ImageIcon ii = new ImageIcon(this.getClass().getResource("C:\\Users\\Name\\workspace\\Craft\\src\\resource\\craft.png"));
image = ii.getImage();
x = 40;
y = 60;
}
This one above is my current try while the example suggests:
ImageIcon ii = new ImageIcon(this.getClass().getResource(craft));
Upvotes: 0
Views: 1042
Reputation: 21223
The exception is thrown from ImageIcon
constructor. Looks from the sample like ImageIcon
is initialized with URL
, this constructor:
String craft = "craft.png";
...
ImageIcon ii = new ImageIcon(this.getClass().getResource(craft));
The reason is probably due to the missing file "craft.png" in your workspace. Make sure that loader can find the specified file and this.getClass().getResource(craft)
is not null.
See Loading Images Using getResource tutorial for details and some examples how to add and load images and other resources.
Upvotes: 2
Reputation: 124215
this.getClass().getResource
is mainly used if you run code from jar file and you need to load resources that are also inside jar.
In your case you should probably just load it as
ImageIcon ii = new ImageIcon("C:/Users/Name/workspace/Craft/src/resource/craft.png");
image = ii.getImage();
or maybe even
ImageIcon ii = new ImageIcon("craft.png");
image = ii.getImage();
if your image is inside of your project.
Upvotes: 2