FileDocCategorySizeDatePackage
BlinkinLED.javaAPI DocExample2207Wed Apr 04 10:30:28 BST 2001duncan

BlinkinLED.java

//Title:       Blinking LED
//Copyright:   Copyright (c) 2001
//Authors:     John Fenton & Duncan Mullier
//Company:     LMU
//Description: Start and Stop buttons added by JF

package duncan;

import java.awt.*;
import java.applet.*;
import java.lang.Runnable; //step 1
import java.awt.event.*;

public class BlinkinLED extends Applet implements Runnable,ActionListener //step 2
{
  Button startBut,stopBut;
	Thread LEDThread; //step 3 
	boolean LEDon; //Changed - can now be set to false by Stop Button 
	boolean LEDlight=false;

	public void init()
	{
    startBut = new Button("Start");
    stopBut = new Button("Stop");
    startBut.addActionListener(this);
    stopBut.addActionListener(this);
    add(startBut);
    add(stopBut);
		//LEDThread = new Thread(this,"LED"); //step 4
		//LEDThread.start();	//step 5
	}//end init

  public void actionPerformed(ActionEvent ae)
  {
    if(ae.getSource() == startBut)
    {
         LEDon = true;
         LEDThread = new Thread(this,"LED"); //step 4
         LEDThread.start();//step 5
    }
    if(ae.getSource() == stopBut)
    {
      LEDon = false;
      LEDlight = false;
      repaint();
    }
  }

  public void update(Graphics g) //avoids flicker
  {
     paint(g);
  }
	
	public void paint(Graphics g)
	{//here the paint( ) method is reading variable LEDlight that is changed by our thread
		//run toggles LEDlight every 1/2 sec; note that run explicitly calls repaint()
		//which calls update()
		if (LEDlight == true) //LEDon?
			g.setColor(Color.red);
		else						//if not black
			g.setColor(Color.black);
		g.fillOval(100,100,50,50);
	}//end paint
	
	public void run() //step 6
	{
		//for(;;)//loop forever REMOVED NOW
			while (LEDon == true)
			{
				LEDlight = !LEDlight; //toggle the LED status
				repaint();	//call paint so it draws the LED in its new state
				try{//we'll talk about try..catch next week
					LEDThread.sleep(500); //wait for 500 milliseconds (1/2 second)
				}catch(InterruptedException e) 
				{
					showStatus("Thread timed out");
				}
				showStatus("LED = "+LEDlight);
			}//end while
	//}//endfor REMOVED
	}//endrun
}//end applet