Animating a Sequence of Images

Threads can be used for implementing animation in Java.Threads are ideals for anything that takes up a lot of time and run continuously. The Applet needs to implements the Runnable interface.


import java.applet.*;

import java.awt.Graphics;

import java.awt.Image;

import java.lang.Math;

public class BlinkItem extends Applet implements Runnable


           //An image that holds two images

               Image imPicc[];

         //keepstracks of which image is displayed

               int iPiccIndex=0;

               Thread imgThreadd;

     public void init()


           //dimension the image array

                 imPicc=new Image[2];

           //load the two images




public void paint(Graphics grph)


               //Calls the update() to avoid image flicking





                       public void update(Graphics grphh)/* update()clears the screen of existing content (existing content means pics(a1&a2)*/



                                   if(imPicc[iPiccIndex]==null)//if images(a1&a2 )is unable to load)


                                        grphh.drawString("Error pic not Found",10,170);



                                         grphh.drawImage(imPicc[iPiccIndex],10,10,this);//draw images


     public void start()


                   //if NO thread is started, it starts the thread

                         if(imgThreadd==null)//Calls the Thread run()


                                 imgThreadd=new Thread(this);//this is the reference

                                 imgThreadd.start();//start the thread



     public void stop()





     public void run()


               for(;;)//run an infinite loop



                         //switch images(a1&a2)

                        iPiccIndex=iPiccIndex==0?1:0;//Ternary operator

   /*sleep() below might be interrupted and cause an interruptedException which is caught*/




                                      Thread.sleep((int) (Math.random()*500));


                      catch(Exception interexcep)//if any error in try block


                               System.out.println("Error….."+ interexcep);



           }//end of run()

     }//end of class BlinkItem

//<applet code="BlinkItem.class" width=500 height=500></applet>

 animation in Java Applet


In this example the Applet get loaded ,the two set of images are animated. As soon as the Thread object is instantiated in the start() the run() which runs as infinite for loop.

The repaint() calls the paint(), which is turn calls the update(). The update() method is overridden to avoid flickering of images.

The Thread object is created to hold the thread.

The applet’s start() is to be overridden to create a thread and start it running.

The runnable interfaces run() is overridden to make the applet run.

The “this” keyword is used to refer to the current thread object.