MMJZ
MMJZ

Reputation: 163

Storing ImageIcons

I got me 90 odd images that form an explosion animation. When I come to 'play' the animation, I use a Swing Timer to set a new Icon for a JLabel, and cycle through until I reach the last image.

My question is this: is it better to have loaded and stored all the ImageIcons in some static form somewhere, or load them from file every time I need them?

Explosions are quite common in the game, and I have two sizes of them (scaling each image for every size of explosion seemed rather inefficient when I want them to swap very quickly) which makes for 200 images (roundabout).

Store or load?

Upvotes: 0

Views: 56

Answers (2)

camickr
camickr

Reputation: 324128

I use a SwingTimer to set a new Icon for a JLabel, and cycle through until I reach the last image.

You may want to consider using an Animated Icon. It can be used anywhere an Icon can be used.

The AnimatedIcon class uses loaded Icons, so I guess my answer would be to pre-load for ease of use and CPU efficiency.

Upvotes: 1

Durandal
Durandal

Reputation: 20059

For a game, using Swing components to represent game objects (Sprites) is probably not the best way. I would use a single JPanel as the rendering component and override its paintComponent() method to do rendering for my own game objects.

This way you avoid dealing with Swing components intricacies (e.g. they may add unwanted gaps / offsets where they really paint, as well they make it harder to control the painting order - important when two objects overlap).

I wouldn't use any type of Icon, just use java.awt.Image, or you own type to represent an image (e.g. to render part of an underlying image - as sprite sheet requires). Icon doesn't really add any value for a game.

If the image data fits easily into memory, I would load all the images before even starting. If there are too many images to preload them all, I would use some sort of cache that retains as many images as possible - the cache may use an LRU based scheme to decide which images to retain when it gets full.

Upvotes: 2

Related Questions