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

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

 

 

 

import java.applet.*;

import java.awt.*;



public class appletanimator2 extends Applet implements Runnable {



public Thread animationthread = null;



//"maxitems" will be used to indicate the number of

//images that exist.

int maxitems=0;



//"sleeptime" indicates the delay between each image

//in milliseconds.

int sleeptime=0;

Image images[];

int currentimage=0;



public void init()

{

    //Get the value of the parameter "maxitems"

    //with the number base 10.

    maxitems=getIntegerParameter("maxitems",10);



    //Get the value of the parameter "sleeptime".

    sleeptime=getIntegerParameter("sleeptime",10);



    //The array "images" will have "maxitems" number

    //of elements.

    images=new Image[maxitems];

    MediaTracker tracker=new MediaTracker(this);    

    for (int i=0; i<maxitems; i++)
{
//The following line will read the values of the
//parameters "image0", "image1", "image2" and so on
//up to the value that maxitems indicates. It will also
//use the strings to load the files specified in those
//parameters.
images[i]=getImage(getDocumentBase()
,getParameter("image"+i)); //The ID number for each image must be increased //for each image you add to the tracker. tracker.addImage(images[i],i); } //Finally we make sure that the tracker loads the images. try {tracker.waitForAll();} catch(InterruptedException e) { System.out.println("Something happened while reading images..."); } } public int getIntegerParameter(String name, int base) { String value=getParameter(name); int intvalue; try {intvalue=Integer.parseInt(value,base);} catch (NumberFormatException e) {return 0;} return intvalue; } public void start() { if (animationthread == null) { animationthread = new Thread(this,"animationthread"); animationthread.start(); } } public void stop() { if ((animationthread != null) && animationthread.isAlive()) animationthread.stop(); animationthread = null; } public synchronized void paint(Graphics g) { //The integer "currentimage" is used as index //for the "images" array. g.drawImage(images[currentimage],0,0,this); } public void update(Graphics g) { paint(g); } public void run() { while (true) { update(getGraphics()); //"currentimage" is increased so that the next //image is displayed in the next screen update. currentimage++; //However it must not exceed the value //of maxitems minus 1. if (currentimage>maxitems-1) currentimage=0; //The variable sleeptime sets //the delay in milliseconds. try {Thread.sleep(sleeptime);} catch(InterruptedException e) {} } } }