Hello. I’ve made a class that is very similiar to the ImageLoader class that is used in Killer Game Programing in java. For anyone who doesn’t know it reads image names from a text file and loads them into maps. I’ve altered how it reads so I can use my own formatting in the text file. Also the original uses this bit of code…
BufferedImage im = ImageIO.read(
getClass().getResource(IMAGE_DIR + fnm) );
Which is great if the images are in the same directory as the class file as the image loader. But I wanted to have the image loader in a different package. So I pass an Object, any object into the constructor and it gives that the name locator, so I can load images in a similar like this…
BufferedImage im = ImageIO.read(locator.getClass().getResource(fileName));
I was wondering if passing any object to help locate the image files is considered a code smell? It seemed like a very easy way to do it.
My second question is about using a MediaTracker. I have added a MediaTracker, and I wanted to check that I have used it correctly or if I even need it at all.
private BufferedImage loadImage(String fileName) {
try {
BufferedImage im = ImageIO.read(locator.getClass().getResource(fileName));
mediaTracker.addImage(im, imageCount++ );
int transparency = im.getColorModel().getTransparency();
BufferedImage copy = graphicsConfiguration.createCompatibleImage(
im.getWidth(), im.getHeight(), transparency);
Graphics2D g2d = copy.createGraphics();
g2d.drawImage(im, 0, 0, null);
g2d.dispose();
return copy;
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
}
I’m not sure what is happening. When imageIo reads the image, does it wait for it to read before continuing? If that is the case then would I really need a media tracker. I could just add a boolean method in the ImageLoader class called finishedLoading() and continue asking in the loop before drawing the images. Or maybe there is a way to just pause the thread like the MediaTracker method waitForAll(). I really need to relearn about threads.
Any help will be much appreciated.