|
Code Samples Index
These code examples and other materials are subject to Sun Microsystems, Inc.
Legal Terms
Animating an Array of Images in an Application
This is the simplest application to animate a an array of images.
import java.awt.*;
import javax.swing.*;
public class AnimApp extends JComponent
implements Runnable {
Image[] images = new Image[2];
int frame = 0;
public void paint(Graphics g) {
Image image = images[frame];
if (image != null) {
g.drawImage(image, 0, 0, this);
}
}
public void run() {
images[0] = new ImageIcon(
"image1.gif").getImage();
images[1] = new ImageIcon(
"image2.gif").getImage();
int delay = 1000; // 1 second
try {
while (true) {
frame = (frame+1)%images.length;
repaint();
Thread.sleep(delay);
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
AnimApp app = new AnimApp();
JFrame frame = new JFrame();
frame.getContentPane().add(app);
frame.setSize(300, 300);
frame.setVisible(true);
(new Thread(app)).start();
}
}
|
Examplets provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.
Order this book from Amazon
|