I am implementing a board game where each player has several units and each unit is shown to a user using a common image which I read from a file using the following method. I read this image at application startup and going to use it later.
private static BufferedImage readBufferedImage (String imagePath) {
try {
InputStream is = IconManager.class.getClassLoader().getResourceAsStream(imagePath);
BufferedImage bimage = ImageIO.read(is);
is.close();
return bimage;
} catch (Exception e) {
return null;
}
}
Units differ with various colorful tokens located on the top of that common image.
Before I just add several commonImages to JPanel and tokens were implemented using JLabels which were floating on the top of commonImage
//at startup
ImageIcon commonImage = new ImageIcon(readBufferedImage("image.png"));
...
JPanel panel = new JPanel();
panel.add(commonImage);
panel.add(commonImage);
//located JLabels with token on the top of each commonImage
However, now I want to use JScrollPane instead of JPanel, so I think it is a better approach to drawString() and drawImage() to each commonImage before I show it to a user.
I estimate roughly a number of units as 20. So now every turn for every unit I would need to generate on-the-fly separate BufferedImage with various tokens configuration.
The question is whether I should cache already generated BufferedImages depending on token configuration to extract from cache if the image has been generated before with same configuration?
The question you ask depends on a few factors:
So without having a good knowledge of your application, no one is going to be able to give you an answer accurate for every situation.
In general, if you’re only moving tokens around, it should be quick to implement an
updateand thepaintComponentmethod of the panel your drawing. If you save your base image, token image and the current resulting image (basically what you proposed), I wouldn’t anticipate a performance problem. The key is to do your updating of the image in your customupdatemethod, and always draw the current resulting image in thepaintComponentmethod.Update
For example, you can cache the current display using code similar to this:
When you want to clear the cache, in your method that does the update, you’d set
cachedImage = null;But in your situation,