// An Up/Down Counting Applet - by Derek Molloy

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class UpDownCounterApplet extends Applet implements ActionListener
{
	private Button start, stop, toggle, upDown;
	private TextField countField1, countField2;
	private Counter2 theCounter1, theCounter2;

	public void init() 
	{
	  countField1 = new TextField(10);
	  countField2 = new TextField(10);
	  this.add(countField1);
	  this.add(countField2);

	  start = new Button("Start");
	  start.addActionListener(this);
	  this.add(start);

	  stop = new Button("Stop");
	  stop.addActionListener(this);
	  this.add(stop);

	  toggle = new Button("Toggle");
	  toggle.addActionListener(this);
	  this.add(toggle);

	  upDown = new Button("Up/Down");
	  upDown.addActionListener(this);
	  this.add(upDown);

	  this.theCounter1 = new Counter2(countField1, 100, 0, 200);
	  this.theCounter2 = new Counter2(countField2, 200, 50, 200);
	}
	
	public void actionPerformed(ActionEvent e) 
	{
	  if (e.getSource().equals(start))
	  {
	    this.theCounter1.start();
	    this.theCounter2.start();
	  }
	  else if (e.getSource().equals(stop))
	  {
	    this.theCounter1.stopCounter();
	    this.theCounter2.stopCounter();
	  }
	  else if (e.getSource().equals(toggle))
	  {
	    this.theCounter1.toggleCounter();
	    this.theCounter2.toggleCounter();
	  }
	  else if (e.getSource().equals(upDown))
	  {
	    this.theCounter1.toggleUpDown();
	    this.theCounter2.toggleUpDown();
	  }
	}
} 



class Counter2 extends Thread
{
	private int count, delay, maximum;
	private boolean running = true, paused = false, upDownFlag = true;  //true for up
	private TextField theField;

	
	public Counter2(TextField t, int delay, int startValue, int max)
	{
	  this.theField = t;
	  this.count = startValue;
	  this.delay = delay;
	  this.maximum = max;
	}

	public void run() 
	{
	  while (running) 
	  {
	    theField.setText("Count: "+this.count);

	    if (this.upDownFlag) 
		count++;
	    else 
		count--;

	    if (this.count>this.maximum) running = false;
	    try 
	    { 
	      Thread.currentThread().sleep(this.delay); 

	      synchronized(this) {
                    while (paused)
                        wait();
              }
	    } 
	    catch (InterruptedException e)
	    {  
		theField.setText("Interrupted!");
		this.stopCounter();
	    }   
	  }
	}

	public int getCount() { return count; }

	public void stopCounter() { this.running = false; }

	public synchronized void toggleCounter()
	{ 
	  this.paused = !this.paused; 
	  if (!this.paused) notify();
	}

	public synchronized void toggleUpDown()
	{ 
	  this.upDownFlag = !this.upDownFlag;
	}
}
