# applet multithreading



## rana2103 (Apr 5, 2008)

i hav recently started learning java and was trying a multithreading applet with the foll code.....i want to display 12 pics wid names pic1.gif,pic2.gif......till pic12.gif....its not working and giving me foll exceptions....

Exception in thread "AWT-EventQueue-1" java.lang.ArrayIndexOutOfBoundsException:
12
at s1.update(s1.java:83)
at sun.awt.RepaintArea.updateComponent(RepaintArea.java:239)
at sun.awt.RepaintArea.paint(RepaintArea.java:216)
at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:301)
at java.awt.Component.dispatchEventImpl(Component.java:4486)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThre
ad.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.
java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
ad.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)

at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)



below is d code....ne help wud b highly appreciated ....plz reply soon...

import java.awt.*;
import java.applet.*;

public class s1 extends Applet implements Runnable
{
Image[] img;
Image img2;
static int cnt;

Thread th = null;

public void init()
{
int i=1;
img=new Image[12];
img2= getImage(getDocumentBase(),"image1.gif");

for ( i = 1; i < 13; i++) 
{
String str="pic"+i+".gif";
img[i-1]= getImage(getDocumentBase(),str); 
}

}
public void start()
{

if ( th == null ) 
{
th = new Thread( this );
th.start();
}
}

public void stop()
{
showStatus("Stopping....");
if ( th != null && th.isAlive() )
th.stop();

th = null;

}

public void run() {

while (th != null) {

repaint();

try {

Thread.sleep( 20 );

} catch ( InterruptedException e ) {

// do nothing
}
}
}

public void paint(Graphics g)
{
update(g);

}

public void update(Graphics g)
{
showStatus("Welcome To AstroFun.com.....");

g.drawImage(img2,0,0,this);
g.drawImage(img[cnt],0,0,this);
cnt=cnt+1;
if(cnt>12)
{
cnt=0;
th=null;
}
}
}


----------



## Chicon (Jul 29, 2004)

Hi rana2103,

Welcome to TSG ! 

The mistake is located in the _update_ method.
Indeed, in the statement _g.drawImage(img[cnt],0,0,this);_,
the _cnt_ variable may have reached the value 12.
Regarding the declaration _img=new Image[12];_, the values of _cnt_ may only vary from 0 to 11.
Therefore, the test _if(cnt>12)_ must be replaced by _if(cnt==12)_.


----------

