alink="#996699">

Back Next

Traffic Light

import java.awt.*;
import javax.swing.*;

public class Light extends JApplet 
{
Image light;
boolean red = false;
boolean yellow = false;
boolean green = false;
int i;

public void init() 
{
i=0;
light = getImage(getCodeBase(), "traffic0.gif");
setSize(40,150);
}

public void update(Graphics g)
{
if(i==60)i=0;
if((i%3)==0)turnOn("red");
else if((i%3)==1)turnOn("yellow");
else if((i%3)==2)turnOn("green"); 
try
{
Thread.sleep(100);
}
catch (InterruptedException e){}
i++;
paint(g);
}

public void paint(Graphics g) 
{
g.drawImage(light, 10, 10, this);
if (red) 
{
g.setColor(Color.gray);
g.fillOval(15,45,22,22);
g.setColor(Color.gray);
g.fillOval(15,75,22,22);
g.setColor(Color.red);
g.fillOval(15,15,22,22);
}
if (yellow) 
{
g.setColor(Color.gray);
g.fillOval(15,15,22,22);
g.setColor(Color.gray);
g.fillOval(15,75,22,22);
g.setColor(Color.yellow);
g.fillOval(15,45,22,22);
}
if (green) 
{
g.setColor(Color.gray);
g.fillOval(15,15,22,22);
g.setColor(Color.gray);
g.fillOval(15,45,22,22);
g.setColor(Color.green);
g.fillOval(15,75,22,22);
}
}

public void turnOn(String color) 
{
red = false;
yellow = false;
green = false;
if (color.equals("red")) red = true;
if (color.equals("yellow")) yellow = true;
if (color.equals("green")) green = true;
repaint();
}
}

Up