Home E-Books Special Effects and Game Development in Java The Applet AppletAnimator

Special Effects and Game Development in Java(TM) - The Applet AppletAnimator




import java.applet.*;

import java.awt.*;

public class appletanimator extends Applet implements Runnable {

public Thread animationthread = null;

//The Image array "images" must be global.

Image images[];

//The variable "currentimage" will hold the

//image currently being displayed.

int currentimage=0;

public void init()


    //Init "images" to have four elements.

    images=new Image[4];

    MediaTracker tracker=new MediaTracker(this);

    //We use a for-loop to load the images.

    for (int i=0; i<4; i++)


        //"image0.gif","image1.gif",...,"image3.gif" will be



        //The ID for each image must be increased

        //for each image that is added to the




    //Finally we must make sure the tracker loads the images.

    try {tracker.waitForAll();}

    catch(InterruptedException e)


        System.out.println("Something happened while reading images...");



public void start()


    if (animationthread == null)


         animationthread = new Thread(this,"animationthread");




public void stop()


    if ((animationthread != null) && animationthread.isAlive())


    animationthread = null;


public synchronized void paint(Graphics g)


    //The integer "currentimage" is used as

    //index for the "images" array.



public void update(Graphics g)




public void run()


    while (true)



        //"currentimage" is increased so that the next

        //image is displayed in the next screen update.


        //However, "currentimage" must not exceed the

        //index value of 3.

        if (currentimage>3) currentimage=0;

        try {Thread.sleep(200);}

        catch(InterruptedException e) {}