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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| 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); System.out.println(image.getWidth(null)); System.out.println(ref);
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.