import java.awt.*; import java.awt.event.*; public class AnimatedImage extends java.applet.Applet implements Runnable, MouseListener { Image pics[] = new Image[16]; String srcImages[] = {"swan_dive_lg_wht_19762_001.jpg", "swan_dive_lg_wht_19762_002.jpg", "swan_dive_lg_wht_19762_003.jpg", "swan_dive_lg_wht_19762_004.jpg", "swan_dive_lg_wht_19762_005.jpg", "swan_dive_lg_wht_19762_006.jpg", "swan_dive_lg_wht_19762_007.jpg", "swan_dive_lg_wht_19762_008.jpg", "swan_dive_lg_wht_19762_009.jpg", "swan_dive_lg_wht_19762_010.jpg", "swan_dive_lg_wht_19762_011.jpg", "swan_dive_lg_wht_19762_012.jpg", "swan_dive_lg_wht_19762_013.jpg", "swan_dive_lg_wht_19762_014.jpg", "swan_dive_lg_wht_19762_015.jpg", "swan_dive_lg_wht_19762_016.jpg" }; Image curImage; Thread runner; boolean stopped = true; Image offscreenImage; Graphics offscreenGraphics; Dimension offscreenSize; boolean fDisplayForward = true; public void start() { if (stopped == true) { stopped = false; runner = new Thread(this); runner.start(); addMouseListener(this); } } public void stop() { stopped = true; } public void run() { int i; MediaTracker tracker = new MediaTracker(this); boolean fEnd; showStatus("Loading images..."); for (i = 0; i < pics.length; i++) { pics[i] = getImage(getCodeBase(), "images/" + srcImages[i]); tracker.addImage(pics[i], i); } try { tracker.waitForAll(); if (tracker.isErrorAny()) { showStatus("Error loading images"); } else { showStatus("Images loaded"); } } catch (Exception e) { e.printStackTrace(); } // This helps identify flicker, and ensure double buffering is working setBackground(Color.blue); i = 0; // loop through images while (!stopped) { showStatus(" " + i); // hack, but it works curImage = pics[i]; repaint(); try { Thread.sleep(100); } catch (InterruptedException e) { System.out.println("Exception\n"); } // Calculate the next index i = fDisplayForward ? i + 1 : i - 1; if (i == pics.length) { i = 0; } else if (i == -1) { i = pics.length - 1; } } } public void update(Graphics g) { Dimension d = getSize(); if ((offscreenImage == null) || (d.width != offscreenSize.width) || (d.height != offscreenSize.height)) { offscreenImage = createImage(d.width, d.height); offscreenSize = d; offscreenGraphics = offscreenImage.getGraphics(); } offscreenGraphics.clearRect(0, 0, d.width, d.height); paint(offscreenGraphics); g.drawImage(offscreenImage, 0, 0, null); } public void paint(Graphics g) { Dimension d = getSize(); if (curImage != null) { g.drawImage(curImage, 0, 0, d.width, d.height, this); } } public void destroy() { offscreenGraphics.dispose(); } public void mousePressed(MouseEvent e) { fDisplayForward = !fDisplayForward; } public void mouseReleased(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } }