import uwcse.graphics.*; import java.awt.Color; import java.awt.Font; /** * Display in a graphics window a traffic light and a menu. */ public class TrafficLightView{ // Menu // Upper left corner public static final int XM = 10; public static final int YM = 350; // size public static final int MENU_WIDTH=65; public static final int MENU_HEIGHT=20; // Graphics elements private GWindow window; private Oval[] lights; /** * Create the graphics window and the menu */ public TrafficLightView(TrafficLightController c) { // Create the display window = new GWindow("Traffic light",500,500); window.setExitOnClose(); // Send all the window events to the controller window.addEventHandler(c); // Background window.add(new Rectangle(0,0,500,500,Color.blue,true)); // Create the menu drawMenu(); // Create the lights drawLights(); // Show it window.doRepaint(); } /** * Update the display of the lights according to the model */ public void updateDisplay(TrafficLightModel model) { // Turn off all of the lights for(int i=0; iXM+MENU_WIDTH || y=YM+MENU_HEIGHT*4) return new MouseClickLocation(MouseClickLocation.INACTIVE_AREA); // The click is on one of the button items switch((y-YM)/MENU_HEIGHT) { case 0: // Click on red return new MouseClickLocation(MouseClickLocation.RED); case 1: // Click on yellow return new MouseClickLocation(MouseClickLocation.YELLOW); case 2: // Click on green return new MouseClickLocation(MouseClickLocation.GREEN); case 3: // Click on animate return new MouseClickLocation(MouseClickLocation.ANIMATE); default: // never get here (but the compiler can't tell) return new MouseClickLocation(MouseClickLocation.INACTIVE_AREA); } } /** * Draw the menu */ private void drawMenu() { // Create the buttons // Upper left corner of each button int x = XM; int y = YM; String[] labels = {"Red", "Yellow", "Green", "Animate"}; Font font = new Font("Times",Font.BOLD,15); for(int i=0; i<4; i++) { window.add(new Rectangle(x,y,MENU_WIDTH,MENU_HEIGHT,Color.black,false)); // label window.add(new TextShape(labels[i],x+5,y,Color.black,font)); // next menu item y+=MENU_HEIGHT; } } /** * Draw the lights in the window */ private void drawLights() { // Create the lights (red,yellow,green) // box of the traffic light window.add(new Rectangle(200,50,100,300,Color.black,true)); // lights: each light is in a container Color[] colors = {Color.red,Color.yellow,Color.green}; lights = new Oval[3]; int x=210, y=60; // upper right corner of the red light for(int i=0; i<3; i++) { // light frame window.add(new Oval(x,y,80,80,colors[i],true)); // light lights[i] = new Oval(x+2,y+2,76,76,Color.black,true); window.add(lights[i]); // next light y+=100; } } }