Program Statement: Write a JAVA program that simulates a traffic light. The program lets the user select one of the three lights: red, yellow, green. When a radio button is selected, the light is turned on, and only one light can be on at a time. No light is on when the program starts.


Tested on:

Software: Windows 8, Jdk 1.6,   Netbeans IDE

Hardware: Intel Core i3, 4 GB RAM, 500 GB HDD




Source Code

@Author: Praveen Kanwar
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/* <applet code="TrafficLights" width=500 height=500> </applet> */
public class TrafficLights extends Applet implements ItemListener
{
    CheckboxGroup cbg;
    Checkbox r,g1,y;
    public void init()
    {
        cbg=new CheckboxGroup();
        r=new Checkbox("Red",cbg,false);
        g1=new Checkbox("Green",cbg,false);
        y=new Checkbox("Yellow",cbg,false);
        r.addItemListener(this);
        g1.addItemListener(this);
        y.addItemListener(this);
        add(r);
        add(g1);
        add(y);
    }
    public void itemStateChanged(ItemEvent ie)
    {
        repaint();
    }
    public void paint(Graphics g)
    {
        if(cbg.getSelectedCheckbox()==r)
        {
            g.setColor(Color.red);
            g.fillOval(150, 125,70,70);
        }
        if(cbg.getSelectedCheckbox()==g1)
        {
            g.setColor(Color.green);
            g.fillOval(150, 125,70,70);
        }
        if(cbg.getSelectedCheckbox()==y)
        {
            g.setColor(Color.yellow);
            g.fillOval(150, 125,70,70);
        }
    }
}

Output


Post a Comment

  1. THANK YOU ....VERY NICE AND WELL SIMPLIFIED

    ReplyDelete
  2. It was asking main method was missing

    ReplyDelete
    Replies
    1. Applets do not require main method to run. Applets and Servlets do not start their own process. Instead they run inside a container. Therefore, they do no need a static main method (which starts the process), but a way to interact with their container.

      Delete
    2. give the same file name which is used in main method

      Delete

 
Top