CSC 8310 -- Traffic Light Applet

Dr. David Matuszek,   dave@acm.org
Fall 1998, Villanova University

This program draws a traffic light. You can change the color of the light by clicking on the appropriate button.

A BorderLayout is used, with a Panel on the north to contain the buttons, and a Canvas in the center to hold the drawing.

Note: This is a picture of the applet, not the applet itself. The applet itself is not included because Java 1.1 is not supported on Netscape browsers.


 


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

/**
 * This applet draws a traffic light.  The user controls the color of
 * the light (red, yellow, green) by clicking one of three buttons.
 * HTML:  <applet code="TrafficLight.class" width=200 height=200></applet>
 */

public class TrafficLight extends Applet
{
  Button redButton    = new Button ("Red");
  Button yellowButton = new Button ("Yellow");
  Button greenButton  = new Button ("Green");

  Color currentColor = Color.red;

  Panel controls = new Panel ();
  DrawingArea drawingArea = new DrawingArea ();
  
  public void init ()
  {
    setLayout (new BorderLayout ());
    add (BorderLayout.NORTH, controls);
    controls.add (redButton);
    controls.add (yellowButton);
    controls.add (greenButton);

    add (BorderLayout.CENTER, drawingArea);

    redButton.addActionListener (new ActionListener () {
      public void actionPerformed (ActionEvent event)
	{
	  changeColor (Color.red);
	}
    });

    yellowButton.addActionListener (new ActionListener () {
      public void actionPerformed (ActionEvent event)
	{
	  changeColor (Color.yellow);
	}
    });

    greenButton.addActionListener (new ActionListener () {
      public void actionPerformed (ActionEvent event)
	{
	  changeColor (Color.green);
	}
    });

    repaint ();
  }

  public void paint (Graphics g)
  {
    drawingArea.paint (drawingArea.getGraphics ());
  }
  
  void changeColor (Color newColor)
  {
    currentColor = newColor;
    repaint ();
  }
  
  class DrawingArea extends Canvas
  {
    public void paint (Graphics da)
    {
      da.setColor (Color.darkGray);
      da.fillRect (70, 20, 50, 150);
      da.setColor (currentColor == Color.red    ? Color.red    : Color.gray);
      da.fillOval (80, 30, 30, 30);
      da.setColor (currentColor == Color.yellow ? Color.yellow : Color.gray);
      da.fillOval (80, 80, 30, 30);
      da.setColor (currentColor == Color.green  ? Color.green  : Color.gray);
      da.fillOval (80, 130, 30, 30);
    }
    
  }
}