Bonjour,
I'm trying my hand at animation, and have found myself a strip of explosions on a single image in a row. I want them to show one after the other in sequence to animate an explosion. Naturally, I'm thinking ImageIcon
on JLabel
, but when I looked at the JLabel
spec I found this line:
JLabel(Icon icon)
-- Creates aJLabel
instance with the specified image. The label is centered vertically and horizontally in its display area.
I want to be able to show only part of a full image in the label, then load another part of it: basically loading the different stages on the one image.
Is there a way to do this without cutting up the image and loading each one individually?
Add the label to a JScrollPane and set the size of the scrollpane to be the width of the individual image. You may also want to remove the boder of the scrollpane and make sure the scrollpane doesn't display scrollbars.
Use a Swing Timer to schedule the animation.
Every time the Timer fires you can change the viewport position of the scrollpane by using the setViewPosition method of the viewport.
You could load the image initially using a
BufferedImage
, whereby you could callgetSubimage
to obtain a cropped copy of theImage
while retaining the originalImage
You could also paint the image using this
drawImage
method from theGraphics
class to crop the image being drawnSee an example here that uses a single animation sprite to choose different location of the image to draw.
Prior to 20JAN15, the sample program pointed to from this answer (which was used to create the animated display of the explosion above) had logic errors and only showed 2 rows of images. (Note that the example doesn't show the last row of the explosion...)
Please see the additional answer on the pointed to-page which contains fixes to the program. Cheers. Warren K.