// program to demonstrate animation techniques import java.awt.*; import java.applet.*; public class animate extends Applet implements Runnable { static final int NUMBER_OF_FRAMES = 36; static final int TIME_ASLEEP = 50; // 50 milliseconds sleep time Image[] gifImages = new Image[NUMBER_OF_FRAMES]; int index = 0; // index to gifImages array int width = 500; // width of offscreen graphics area int height = 500; // height of offscreen graphics area Image offScreenImage; Graphics offScreenGraphics; MediaTracker tracker; Thread appletThread; public void init() { // load images into array tracker = new MediaTracker(this); for (int index=0; index != gifImages.length; index++) { gifImages[index] = getImage(getDocumentBase(), "images\\j"+index+".gif"); tracker.addImage(gifImages[index],index); } try { tracker.waitForAll(); } catch (InterruptedException e){} offScreenImage = createImage(width,height); offScreenGraphics = offScreenImage.getGraphics(); } public void paint(Graphics g) { int topLeftX=100; // abscissa of top left-hand corner of image int topLeftY=100; // ordinate top left-hand corner of image // get width and height of image and scale by 50% int imageWidth = (gifImages[index].getWidth(this))/2; int imageHeight = (gifImages[index].getHeight(this))/2; // erase previous image from off screen graphics area offScreenGraphics.setColor(Color.white); offScreenGraphics.fillRect(0,0,width,height); // draw next image in off screen graphics area offScreenGraphics.drawImage(gifImages[index], topLeftX, topLeftY, imageWidth, imageHeight, this); // draw image on the applet's screen g.drawImage(offScreenImage,0,0,width,height,this); } // create new thread public void start() { if (appletThread == null) { appletThread=new Thread(this); appletThread.start(); } } // override run() method to display the images on the screen public void run() { Graphics g = getGraphics(); while (true) { paint(g); index++; index = index % NUMBER_OF_FRAMES; try{appletThread.sleep(TIME_ASLEEP);} catch (InterruptedException e){} } } public void destroy() { if (appletThread != null) { appletThread.stop(); appletThread=null; } } }