• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why isnt my thread rerstarted?

 
Rajani Deshpande
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Please have a look at my code. It displays a sequence of images . if the user clicks on any of the buttons, my timer thread has to sleep for 5 secs before it shows the next image. but when i run this code, when the buttons are clicked, the delay becomes smaller and smaller.
please check

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;

public class Album extends Applet implements ActionListener, Runnable
{
Button nextBtn,backBtn,firstBtn,lastBtn;
Panel btnPanel;
int count, lastcount;
Image pictures[];
Thread timer;
boolean shouldRun;
boolean increment = false;
public void init()
{
this.setBackground(Color.black);
setLayout(new BorderLayout());
nextBtn = new Button("Next");
backBtn = new Button("Back");
firstBtn = new Button("First");
lastBtn = new Button("Last");
btnPanel =new Panel();
btnPanel.setLayout(new FlowLayout());
btnPanel.add(nextBtn);
btnPanel.add(backBtn);
btnPanel.add(firstBtn);
btnPanel.add(lastBtn);
add(btnPanel,BorderLayout.NORTH);
nextBtn.addActionListener(this);
lastBtn.addActionListener(this);
firstBtn.addActionListener(this);
backBtn.addActionListener(this);
lastcount = 5;
pictures = new Image[10];
MediaTracker tracker = new MediaTracker(this);
for (int a = 0; a < lastcount; a++)
{
pictures[a] = getImage (getCodeBase
(), "image00"+a+".jpg");
tracker.addImage(pictures[a], 0);
}
try
{
tracker.waitForAll();
}
catch(InterruptedException e)
{
System.out.println(e);
}
count = 0;

}
public void start()
{
if (timer==null)
{
timer = new Thread(this);
shouldRun = true;
timer.start();
}
}
public void run()
{
while(shouldRun)
{
if (increment)
{
count++;
count %= lastcount;// wrap around to zero
repaint();
}
try
{
Thread.sleep(5000);
increment = true;
}
catch(Exception e)
{
System.out.println("Interrupted");
}
}
timer = null;
System.out.println("DYING..........");
}
public void stop()
{
timer = null;
}
public void paint(Graphics g)
{
int wd = pictures[count].getWidth(this);
int ht = pictures[count].getHeight(this);
System.out.println(count +" "+ wd+" " +ht);
resize(wd,ht);
g.drawImage(pictures[count], 0, 0, this);
}

public void actionPerformed(ActionEvent evt)
{
String command = evt.getActionCommand();
if (command=="Next")
{
count += 1;
}
else if(command =="Back")
{
count-=1;
if (count == -1) count = lastcount-1 ;
}
else if (command =="First")
{
count = 0;
}
else if (command =="Last")
{
count = lastcount - 1;
}
count %= lastcount;// wrap around to zero
repaint ();// causes update as soon as possible
shouldRun = false;
increment = false;
timer = null;
start();
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic