/*
 * StopWatch.java
 * copyright (c) since 2004 "Kimmy" all right reserved.
 */

/*
<applet code="StopWatch.class" width=400 height=300>
</applet>
*/

import java.applet.*;
import java.awt.*;
import java.util.*;
  
public class StopWatch extends Applet implements Runnable{
 
  public Thread clock;
  public Button start, stop;
  public Checkbox lap;
  public Font font;
  public int time, add, count;
 
  public Dimension d;
  public Image offScreen;
  public Graphics offGraphics;
 
  public void init(){
    this.setBackground(Color.white);
    d = this.getSize();
    offScreen = createImage(d.width, d.height);
    offGraphics = offScreen.getGraphics();
 
    start = new Button("Start");
    stop = new Button("Stop");
    lap = new Checkbox("Lap");
    this.add(start);
    this.add(stop);
    this.add(lap);                                                                      
    time = 0;
    add = 0;
    font = new Font("TimesRoman", Font.PLAIN, 48);
  }

  public void start(){
    if(count!=0 && clock==null){
      clock = new Thread(this);
      clock.start();
      time = 0;
    }
  }

  public void stop(){
    if(clock!=null){
      clock = null;
    }
  }

  public void run(){
    while(clock!=null){
      if(lap.getState()){
        add++;
      }else{
        time++;
      }
      repaint();
      try{
        Thread.sleep(10);
      }
      catch(InterruptedException e){
      }
    }
  }
                                                                               
  public void paint(Graphics g){
    offGraphics.clearRect(0, 0, d.width, d.height);
    offGraphics.setFont(font);
    if(time%10==0){
      offGraphics.drawString((time/100.0)+"0", 150, 200);
    }else{
      offGraphics.drawString((time/100.0)+"", 150, 200);
    }
    g.drawImage(offScreen, 0, 0, this);
  }

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

  public boolean action(Event ev, Object arg){
    if(ev.target instanceof Button){
      if(arg.equals("Start")){
        count++;
        this.start();
      }else if(arg.equals("Stop")){
        this.stop();
      }
    }else if(ev.target instanceof Checkbox){
      if(!(((Checkbox)ev.target).getState())){
        time += add;
        add = 0;
      }
    }
    return true;
  }

}







