import java.awt.Color; //use Color class import uwcse.graphics.*; /** A class to display and action a traffic light */ public class TrafficLight { // instance fields private GWindow window; private Oval red; private Oval yellow; private Oval green; /** * Construct the traffic light */ public TrafficLight() { // Window: 170x250 with the "Traffic light" title window = new GWindow("Traffic light", 170, 250); // Enclose the circles in a box Rectangle r = new Rectangle(50, 50, 50, 150, Color.black, true); window.add(r); // Circles of the traffic light // all in a vertical line with a diameter of 50 pixels // initially the light is green red = new Oval(50, 50, 50, 50, Color.red, false); window.add(red); yellow = new Oval(50, 100, 50, 50, Color.yellow, false); window.add(yellow); green = new Oval(50, 150, 50, 50, Color.green, true); window.add(green); // show the traffic light window.doRepaint(); } /** * Set the traffic light to green */ public void setToGreen() { // remove all circles and create new ones with the right fill window.remove(red); window.remove(yellow); window.remove(green); red = new Oval(50, 50, 50, 50, Color.red, false); window.add(red); yellow = new Oval(50, 100, 50, 50, Color.yellow, false); window.add(yellow); green = new Oval(50, 150, 50, 50, Color.green, true); window.add(green); // Show it window.doRepaint(); } /** * Set the traffic light to yellow */ public void setToYellow() { // remove all circles and create new ones with the right fill window.remove(red); window.remove(yellow); window.remove(green); red = new Oval(50, 50, 50, 50, Color.red, false); window.add(red); yellow = new Oval(50, 100, 50, 50, Color.yellow, true); window.add(yellow); green = new Oval(50, 150, 50, 50, Color.green, false); window.add(green); // Show it window.doRepaint(); // Exit the application when closing the window window.setExitOnClose(); } /** * Set the traffic light to red */ public void setToRed() { // remove all circles and create new ones with the right fill window.remove(red); window.remove(yellow); window.remove(green); red = new Oval(50, 50, 50, 50, Color.red, true); window.add(red); yellow = new Oval(50, 100, 50, 50, Color.yellow, false); window.add(yellow); green = new Oval(50, 150, 50, 50, Color.green, false); window.add(green); // Show it window.doRepaint(); } /** * Entry point of the program */ public static void main(String[] args) { new TrafficLight(); } }