FileDocCategorySizeDatePackage
Counter.javaAPI DocExample1719Wed Apr 04 12:46:52 BST 2001None

Counter.java

// Sample applet demonstrating the continuous display of a counter
// with start, stop & reset buttons
// could be adapted for assignment
// J harvey, April 2001

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.lang.Runnable;

public class Counter extends Applet implements Runnable, ActionListener
{
	private Button start, stop, reset;
	private Panel testPan;
	private TextField T1;
	Thread counterThread;
	boolean on=false;
	private double value=0;
		
	public void init()
	{
	T1 = new TextField(12);
	
	start = new Button("START");
	start.addActionListener(this);
	stop = new Button("STOP");
	stop.addActionListener(this);
	reset = new Button("RESET");
	reset.addActionListener(this);

	
	testPan = new Panel();
	testPan.add(start);
	testPan.add(stop);
	testPan.add(reset);
	testPan.add(T1);
	add(testPan);
	} // end init
	
	public void actionPerformed(ActionEvent ae)
	{
	
	if ((ae.getSource() == start))
		{
			on = true;
			counterThread = new Thread(this, "");
			counterThread.start();
		}
	if ((ae.getSource() == stop))
		{
		on=false;
		repaint();
		}
	if((ae.getSource() == reset))
		{
		if(on==false)  // Don't want reset button to work if on is true
			{
			value=0;
			T1.setText("" + value);
			repaint();
			} // endif
		}	// endif
		
	} // end actionPerformed	
	
	public void paint(Graphics g)
	{
	
	} // end paint
	
	public void run()
	{
	while (on==true)
	{
		value = value+0.05;
		T1.setText("" + value); // output needs formatting properly
		repaint();
	try
		{
	counterThread.sleep(500);
		}
	catch (InterruptedException ie)
		{
		}
		}// end while
	} // end run
} // end Counter