|
TrafficLight |
|
1 // joi/1/lights/TrafficLight.java 2 // 3 // 4 // Copyright 2003 Bill Campbell and Ethan Bolker 5 6 import java.awt.*; 7 import java.awt.event.*; 8 9 /** 10 * A TrafficLight has three lenses: red, yellow and green. 11 * It can be set to signal Go, Caution, Stop or Walk. 12 * 13 * @version 1 14 */ 15 16 public class TrafficLight extends Panel 17 { 18 // Three Lenses and a Button 19 20 private Lens red = new Lens( Color.red ); 21 private Lens yellow = new Lens( Color.yellow ); 22 private Lens green = new Lens( Color.green ); 23 private Button nextButton = new Button("Next"); 24 25 /** 26 * Construct a traffic light. 27 */ 28 29 public TrafficLight() 30 { 31 this.setLayout(new BorderLayout()); 32 33 // create a Panel for the Lenses 34 Panel lensPanel = new Panel(); 35 lensPanel.setLayout( new GridLayout( 3, 1 ) ); 36 lensPanel.add( red ); 37 lensPanel.add( yellow ); 38 lensPanel.add( green ); 39 this.add( BorderLayout.NORTH, lensPanel ); 40 41 // configure the "Next" button 42 Sequencer sequencer = new Sequencer( this ); 43 NextButtonListener payAttention = 44 new NextButtonListener( sequencer ); 45 nextButton.addActionListener( payAttention ); 46 this.add( BorderLayout.CENTER, nextButton); 47 } 48 49 // Methods that change the light 50 51 /** 52 * Set the light to stop (red). 53 */ 54 55 public void setStop() 56 { 57 red.turnOn(); 58 yellow.turnOff(); 59 green.turnOff(); 60 } 61 62 /** 63 * Set the light to caution (yellow). 64 */ 65 66 public void setCaution() 67 { 68 red.turnOff(); 69 yellow.turnOn(); 70 green.turnOff(); 71 } 72 73 /** 74 * Set the light to go (green). 75 */ 76 77 public void setGo() 78 { 79 red.turnOff(); 80 yellow.turnOff(); 81 green.turnOn(); 82 } 83 84 /** 85 * Set the light to walk. 86 * 87 * (In Boston, red and yellow signal walk.) 88 */ 89 90 public void setWalk() 91 { 92 red.turnOn(); 93 yellow.turnOn(); 94 green.turnOff(); 95 } 96 97 /** 98 * The traffic light simulation starts at main. 99 * 100 * @param args ignored. 101 */ 102 103 public static void main( String[] args ) 104 { 105 Frame frame = new Frame(); 106 TrafficLight light = new TrafficLight(); 107 frame.add( light ); 108 frame.addWindowListener( new ShutDownLight() ); 109 frame.pack(); 110 frame.show(); 111 } 112 113 // A ShutDownLight instance handles close events generated 114 // by the underlying window system with its windowClosing 115 // method. 116 // 117 // This is an inner class, declared inside the 118 // TrafficLight class since it's used only here. 119 120 private static class ShutDownLight extends WindowAdapter 121 { 122 // Close the window by shutting down the light. 123 124 public void windowClosing (WindowEvent e) 125 { 126 System.exit(0); 127 } 128 } 129 } 130 131 132
|
TrafficLight |
|