import uwcse.graphics.*; /** * The TrafficLightController manages the interaction between the user * and a traffic light (change colors, animate...) */ public class TrafficLightController extends GWindowEventAdapter{ // By extending GWindowEventAdapter, a TrafficLightController can // receive events generated by mouse clicks or a timer. // To create a traffic light, use a view and a model private TrafficLightView view; private TrafficLightModel model; private boolean isAnimationOn = false; // true if the traffic light is changing colors automatically private int maxCounter = 11; // number of timer intervals in one animation private int counter = 0; // current timer interval in the animation /** * Create the display of a traffic light. The user can interact with * the display via mouse clicks. */ public TrafficLightController() { // the view: // Clicks on the display of the traffic lights // are sent to this TrafficLightController this.view = new TrafficLightView(this); // the model: this.model = new TrafficLightModel(this.view); } /** * A click on the window has been received. Process the user's click. */ public void mousePressed(GWindowEvent e) { // Ignore the event if the animation is going on if (this.isAnimationOn) return; // Click location int x = e.getX(); int y = e.getY(); // Ask the view to define the mouse click in terms of the // relevant areas of the window MouseClickLocation clickLoc = this.view.findClickLocation(x,y); // Process the mouse click switch(clickLoc.area) { case MouseClickLocation.RED: // Click on red this.model.turnRed(); break; case MouseClickLocation.YELLOW: // Click on yellow this.model.turnYellow(); break; case MouseClickLocation.GREEN: // Click on green this.model.turnGreen(); break; case MouseClickLocation.ANIMATE: // Click on animate this.isAnimationOn = true; this.view.startTimerEvents(1000); break; } } /** * Do the animation of the traffic light */ public void timerExpired(GWindowEvent e) { if (this.counter<=this.maxCounter) { this.model.nextColor(); this.counter++; } else { this.isAnimationOn = false; this.counter=0; this.view.stopTimerEvents(); } } }