import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class RTest extends Applet implements Runnable, ActionListener
{
	boolean shouldBeRunning = false; //allows applet to drop gracefully out of run loop
	long start; //start time in milliseconds
	Random r;
	long total = 0, count = 0;
	Button b = null;	


	public void init()
	{
		r = new Random(System.currentTimeMillis());
		//handle restarts
		if (b == null)
		{
			b = new Button("hi");
			this.add(b);
			b.addActionListener(this);
			b.setLocation(10, 10);
		}
		
		this.validate();
	}

	public void start()
	{
		System.out.println("starting");
		shouldBeRunning = true;
		Thread t = new Thread(this);
		t.start();
	}
	public void stop()
	{
		System.out.println("stopping");
		shouldBeRunning = false;
	}

	public void run()
	{
	


		//to allow for dynamic resizing, put these in the run loop. 
		Dimension dApplet = this.getSize();
		Dimension dButton = b.getSize();
		
		while(shouldBeRunning)
		{
			//pause a random interval
			//display a small button in a random location
			//reset start
			if (start == 0)
			{
				start = System.currentTimeMillis();

				int newX, newY;
				newX = r.nextInt();


				newX = constrain(newX, 0, (dApplet.width - dButton.width) );
				newY = r.nextInt();	
				newY = constrain(newY, 0, (dApplet.height - dButton.height) );
				System.out.println(" new x = " + newX + "; new Y = " + newY);
				b.setLocation(newX, newY);
				//this.validate();
				try
				{
					Thread.sleep(200);
				}
				catch(InterruptedException e)
				{
					System.out.println("thread interrupted: " + e);
					shouldBeRunning = false;
				}
			}

			//System.out.println("running");
		}
	}

	//take arg and constrain it between lower and upper bounds
	int constrain(int x, int lo, int hi)
	{
		x = Math.abs(x); //make it positive
		int range = hi - lo;
		x %= range; //restrict x to appropriate range
		x += lo; //translate x range to start at low bound
		return x;
	}

	public void actionPerformed(ActionEvent ae)
	{
		System.out.println("action");
		long stop = System.currentTimeMillis();
		String s1 = "time = " + (stop - start) + " ms";

		total += (stop - start);
		count++;
		System.out.println("total = " + total);
		System.out.println("count = " + count);
		String s2 = "avg time: " + (total / count) + " msec";
		System.out.println( s1 + s2);
		showStatus(s1 + s2);

		start = 0; 
	}


}