So I’m trying to make a simple game and I want the images loaded from the start so I want to create a hashtable that stores the Image with its name as the key. When I call ImageStore.get().getImage(“image name”) from my gameloop, I get an error when the ImageStore is initialized (shown as a comment in the code).
public class ImageStore {
private static ImageStore single = new ImageStore();
public static Hashtable<String, Image> images = new Hashtable<String, Image>();
private ImageStore() {
BufferedImage sourceImage = null;
String dirPath = "images";
File imageDir = new File(dirPath);
imageDir = new File(imageDir.toURI());
String absoluteDirPath = imageDir.getPath();
absoluteDirPath = absoluteDirPath.replace('\\', '/');
imageDir = new File(absoluteDirPath);
File[] imageFiles = imageDir.listFiles();
if (imageFiles.length == 0)
System.out.println("Directory empty");
else {
for (int i = 0; i < imageFiles.length; i++) {
String ref = imageFiles[i].getName();
try {
sourceImage = ImageIO.read(imageFiles[i]);
} catch (IOException e) {
fail("Failed to load: " + ref);
}
GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
Image image = gc.createCompatibleImage(sourceImage.getWidth(), sourceImage.getHeight(), Transparency.BITMASK);
//both of these print values without problems, so neither argument
//passed to the hashtable is null
System.out.println(image.getWidth(null));
System.out.println(ref);
//getting a null pointer exception here
images.put(ref, image);
}
}
}
Also if I’m doing anything in a weird way in the code, let me know of the proper way (I’m new to game programming). Thanks in advance for any help.