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.
public class BlinkItem extends Applet implements Runnable
//An image that holds two images
//keepstracks of which image is displayed
public void init()
//dimension the image array
//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);
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
/*sleep() below might be interrupted and cause an interruptedException which is caught*/
catch(Exception interexcep)//if any error in try block
}//end of run()
}//end of class BlinkItem
//<applet code="BlinkItem.class" width=500 height=500></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.