I have been looking for the null pointer for a few hours, and it feels like I've been wasting away staring at the same screen.
So, I'm attempting to open a SpriteSheet and get an image from that sheet, unfortunately at my best attempts it returns an error.
I believe the Map is the problem; I have a Map that documents the title and directory of a sprite sheet. When I try to access the specified SpriteSheet it returns a NullPointerException.
Anyways, getting to the code:
package main;
import java.util.HashMap;
import java.util.Map;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.SpriteSheet;
public class Resources {
public static Map<String, SpriteSheet> sprites;
public static Map<String, Image> images;
public Resources(){
sprites = new HashMap<String, SpriteSheet>();
images = new HashMap<String, Image>();
try {
sprites.put("Tiles", getSpriteSheet("Tiles.png", 32, 32));
} catch (SlickException e) {
e.printStackTrace();
}
}
private static SpriteSheet getSpriteSheet(String image, int w, int h) throws SlickException{
return new SpriteSheet("/res/" + image, w, h);
}
public static Image getImage(String image, int x, int y) throws SlickException{
Image img = sprites.get("Tiles").getSubImage(x, y);
if(img != null){
return img;
}else{
System.out.println("ERROR LOADING IMAGE");
return null;
}
}
}
答案 0 :(得分:2)
在没有看到堆栈跟踪的情况下,我猜这个问题就出现了:
Image img = sprites.get("Tiles").getSubImage(x, y);
这是因为如果你调用构造函数,你只会为sprites
分配一个值,所以如果在碰巧调用之前调用这个静态方法,你会得到一个NullPointerException
构造
您可以为静态字段指定一个值,如下所示:
public static Map<String, SpriteSheet> sprites = new HashMap<>();
public static Map<String, Image> images = new HashMap<>();
然后删除构造函数中的赋值。
您可能还需要考虑将静态字段设置为private和final,以便最小化可见性,并分别避免意外重新分配。
如果要将Tiles.png
精灵表放入这些静态映射中,可以使用静态初始化块执行此操作:
static {
try {
sprites.put("Tiles", getSpriteSheet("Tiles.png", 32, 32));
} catch (SlickException e) {
// ...
}