Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf ·...

27
© 2002 by Prentice-Hall, Inc. I Elevator View (on CD) I.1 Introduction This appendix contains the implementation for class ElevatorView (Fig. I.1). Familiar- ity with the “Thinking About Objects” sections from all chapters (Chapter 22, in particular) necessitates the understanding of material presented in this appendix. Class Elevator- View is the largest class in the simulation. To facilitate discussion, we have divided the discussion of the ElevatorView into five topics—Class Objects, Class Constants, Class Constructor, Event Handling and Component Diagrams Revisited. 1 // ElevatorView.java 2 // View for ElevatorSimulation 3 package com.deitel.jhtp4.elevator.view; 4 5 // Java core packages 6 import java.awt.*; 7 import java.awt.event.*; 8 import java.util.*; 9 import java.applet.*; 10 11 // Java extension package 12 import javax.swing.*; 13 14 // Deitel packages 15 import com.deitel.jhtp4.elevator.event.*; 16 import com.deitel.jhtp4.elevator.ElevatorConstants; 17 18 public class ElevatorView extends JPanel 19 implements ActionListener, ElevatorModelListener, 20 ElevatorConstants { 21 Fig. I.1 ElevatorView displays the elevator simulation model (part 1 of 18).

Transcript of Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf ·...

Page 1: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

© 2002 by Prentice-Hall, Inc.

IElevator View (on CD)

I.1 IntroductionThis appendix contains the implementation for class ElevatorView (Fig. I.1). Familiar-ity with the “Thinking About Objects” sections from all chapters (Chapter 22, in particular)necessitates the understanding of material presented in this appendix. Class Elevator-View is the largest class in the simulation. To facilitate discussion, we have divided thediscussion of the ElevatorView into five topics—Class Objects, Class Constants,Class Constructor, Event Handling and Component Diagrams Revisited.

1 // ElevatorView.java2 // View for ElevatorSimulation3 package com.deitel.jhtp4.elevator.view;45 // Java core packages6 import java.awt.*;7 import java.awt.event.*;8 import java.util.*;9 import java.applet.*;

1011 // Java extension package12 import javax.swing.*;1314 // Deitel packages15 import com.deitel.jhtp4.elevator.event.*;16 import com.deitel.jhtp4.elevator.ElevatorConstants;1718 public class ElevatorView extends JPanel 19 implements ActionListener, ElevatorModelListener,20 ElevatorConstants {21

Fig. I.1 ElevatorView displays the elevator simulation model (part 1 of 18).

Page 2: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

1439 Elevator View (on CD) Appendix I

22 // ElevatorView dimensions23 private static final int VIEW_WIDTH = 800;24 private static final int VIEW_HEIGHT = 435;2526 // offset for positioning Panels in ElevatorView27 private static final int OFFSET = 10;2829 // Elevator repaints components every 50 ms30 private static final int ANIMATION_DELAY = 50;3132 // horizontal distance constants33 private static final int PERSON_TO_BUTTON_DISTANCE = 400;34 private static final int BUTTON_TO_ELEVATOR_DISTANCE = 50;35 private static final int PERSON_TO_ELEVATOR_DISTANCE = 36 PERSON_TO_BUTTON_DISTANCE + BUTTON_TO_ELEVATOR_DISTANCE;3738 // times walking to Floor's Button and Elevator39 private static final int TIME_TO_BUTTON = 3000; // 3 seconds40 private static final int TIME_TO_ELEVATOR = 1000; // 1 second4142 // time traveling in Elevator (5 seconds)43 private static final int ELEVATOR_TRAVEL_TIME = 5000;4445 // Door images for animation46 private static final String doorFrames[] = {47 "images/door1.png", "images/door2.png", "images/door3.png",48 "images/door4.png", "images/door5.png" };4950 // Person images for animation51 private static final String personFrames[] = { 52 "images/bug1.png", "images/bug2.png", "images/bug3.png", 53 "images/bug4.png", "images/bug5.png", "images/bug6.png",54 "images/bug7.png", "images/bug8.png" };5556 // Light images for animation57 private static final String lightFrames[] = {58 "images/lightOff.png", "images/lightOn.png" };5960 // Floor Light images for animation61 private static final String firstFloorLightFrames[] = {62 "images/firstFloorLightOff.png", 63 "images/firstFloorLightOn.png" };6465 private static final String secondFloorLightFrames[] = {66 "images/secondFloorLightOff.png", 67 "images/secondFloorLightOn.png", };6869 // Floor Button images for animation70 private static final String floorButtonFrames[] = { 71 "images/floorButtonUnpressed.png",72 "images/floorButtonPressed.png",73 "images/floorButtonLit.png" };74

Fig. I.1 ElevatorView displays the elevator simulation model (part 2 of 18).

Page 3: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

Appendix I Elevator View (on CD) 1440

75 // Elevator Button images for animation76 private static final String elevatorButtonFrames[] = {77 "images/elevatorButtonUnpressed.png",78 "images/elevatorButtonPressed.png",79 "images/elevatorButtonLit.png" };8081 // Bell images for animation82 private static final String bellFrames[] = { 83 "images/bell1.png", "images/bell2.png", 84 "images/bell3.png" };8586 private static final String floorImage = 87 "images/floor.png";88 private static final String ceilingImage = 89 "images/ceiling.png";90 private static final String elevatorImage = 91 "images/elevator.png";92 private static final String wallImage = 93 "images/wall.jpg";94 private static final String elevatorShaftImage = 95 "images/elevatorShaft.png";9697 // audio files98 private static final String bellSound = "bell.wav";99 private static final String doorOpenSound = "doorOpen.wav";100 private static final String doorCloseSound = "doorClose.wav";101 private static final String elevatorSound = "elevator.au";102 private static final String buttonSound = "button.wav";103 private static final String walkingSound = "walk.wav";104105 private static final String midiFile = "sounds/liszt.mid";106107 // ImagePanels for Floors, ElevatorShaft, wall and ceiling108 private ImagePanel firstFloorPanel;109 private ImagePanel secondFloorPanel;110 private ImagePanel elevatorShaftPanel;111 private ImagePanel wallPanel;112 private ImagePanel ceilingPanel;113114 // MovingPanels for Elevator115 private MovingPanel elevatorPanel;116117 // AnimatedPanels for Buttons, Bell, Lights and Door118 private AnimatedPanel firstFloorButtonPanel;119 private AnimatedPanel secondFloorButtonPanel;120 private AnimatedPanel elevatorButtonPanel;121 private AnimatedPanel bellPanel;122 private AnimatedPanel elevatorLightPanel;123 private AnimatedPanel firstFloorLightPanel;124 private AnimatedPanel secondFloorLightPanel;125 private AnimatedPanel doorPanel;126

Fig. I.1 ElevatorView displays the elevator simulation model (part 3 of 18).

Page 4: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

1441 Elevator View (on CD) Appendix I

127 // List containing AnimatedPanels for all Person objects128 private java.util.List personAnimatedPanels;129130 // AudioClips for sound effects131 private AudioClip bellClip;132 private AudioClip doorOpenClip;133 private AudioClip doorCloseClip;134 private AudioClip elevatorClip;135 private AudioClip buttonClip;136 private AudioClip walkClip;137138 // ElevatorMusic to play in Elevator139 private ElevatorMusic elevatorMusic;140141 // Timer for animation controller; 142 private javax.swing.Timer animationTimer;143144 // distance from top of screen to display Floors145 private int firstFloorPosition;146 private int secondFloorPosition;147148 // Elevator's velocity149 private double elevatorVelocity;150151 // ElevatorView constructor152 public ElevatorView()153 {154 // specifiy null Layout155 super( null );156157 instantiatePanels();158 placePanelsOnView();159 initializeAudio();160161 // calculate distance Elevator travels162 double floorDistance = 163 firstFloorPosition - secondFloorPosition;164165 // calculate time needed for travel166 double time = ELEVATOR_TRAVEL_TIME / ANIMATION_DELAY;167168 // determine Elevator velocity (rate = distance / time)169 elevatorVelocity = ( floorDistance + OFFSET ) / time;170171 // start animation Thread172 startAnimation();173174 } // end ElevatorView constructor175176 // instantiate all Panels (Floors, Elevator, etc.)177 private void instantiatePanels()178 {

Fig. I.1 ElevatorView displays the elevator simulation model (part 4 of 18).

Page 5: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

Appendix I Elevator View (on CD) 1442

179 // instantiate ImagePanels representing Floors180 firstFloorPanel = new ImagePanel( 0, floorImage );181 secondFloorPanel = new ImagePanel( 0, floorImage );182183 // calculate first and second Floor positions184 firstFloorPosition = 185 VIEW_HEIGHT - firstFloorPanel.getHeight();186 secondFloorPosition = 187 ( int ) ( firstFloorPosition / 2 ) - OFFSET;188189 firstFloorPanel.setPosition( 0, firstFloorPosition );190 secondFloorPanel.setPosition( 0, secondFloorPosition );191192 wallPanel = new ImagePanel( 0, wallImage );193194 // create and position ImagePanel for ElevatorShaft195 elevatorShaftPanel = 196 new ImagePanel( 0, elevatorShaftImage );197198 double xPosition = PERSON_TO_ELEVATOR_DISTANCE + OFFSET;199 double yPosition = 200 firstFloorPosition - elevatorShaftPanel.getHeight();201202 elevatorShaftPanel.setPosition( xPosition, yPosition );203204 // create and position ImagePanel for ceiling205 ceilingPanel = new ImagePanel( 0, ceilingImage );206207 yPosition = elevatorShaftPanel.getPosition().getY() -208 ceilingPanel.getHeight();209210 ceilingPanel.setPosition( xPosition, yPosition );211212 // create and position MovingPanel for Elevator213 elevatorPanel = new MovingPanel( 0, elevatorImage );214215 yPosition = firstFloorPosition - elevatorPanel.getHeight();216217 elevatorPanel.setPosition( xPosition, yPosition );218219 // create and position first Floor Button220 firstFloorButtonPanel = 221 new AnimatedPanel( 0, floorButtonFrames );222223 xPosition = PERSON_TO_BUTTON_DISTANCE + 2 * OFFSET;224 yPosition = firstFloorPosition - 5 * OFFSET;225 firstFloorButtonPanel.setPosition( xPosition, yPosition );226227 int floorButtonPressedFrameOrder[] = { 0, 1, 2 };228 firstFloorButtonPanel.addFrameSequence( 229 floorButtonPressedFrameOrder );230

Fig. I.1 ElevatorView displays the elevator simulation model (part 5 of 18).

Page 6: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

1443 Elevator View (on CD) Appendix I

231 // create and position second Floor Button232 secondFloorButtonPanel = 233 new AnimatedPanel( 1, floorButtonFrames );234235 xPosition = PERSON_TO_BUTTON_DISTANCE + 2 * OFFSET;236 yPosition = secondFloorPosition - 5 * OFFSET;237 secondFloorButtonPanel.setPosition( xPosition, yPosition );238239 secondFloorButtonPanel.addFrameSequence( 240 floorButtonPressedFrameOrder );241242 // create and position Floor Lights243 firstFloorLightPanel = 244 new AnimatedPanel( 0, firstFloorLightFrames );245246 xPosition = elevatorPanel.getLocation().x - 4 * OFFSET;247 yPosition = 248 firstFloorButtonPanel.getLocation().y - 10 * OFFSET;249 firstFloorLightPanel.setPosition( xPosition, yPosition );250251 secondFloorLightPanel = 252 new AnimatedPanel( 1, secondFloorLightFrames );253254 yPosition = 255 secondFloorButtonPanel.getLocation().y - 10 * OFFSET;256 secondFloorLightPanel.setPosition( xPosition, yPosition );257258 // create and position Door AnimatedPanels259 doorPanel = new AnimatedPanel( 0, doorFrames );260 int doorOpenedFrameOrder[] = { 0, 1, 2, 3, 4 };261 int doorClosedFrameOrder[] = { 4, 3, 2, 1, 0 };262 doorPanel.addFrameSequence( doorOpenedFrameOrder );263 doorPanel.addFrameSequence( doorClosedFrameOrder );264265 // determine where Door is located relative to Elevator266 yPosition = 267 elevatorPanel.getHeight() - doorPanel.getHeight();268269 doorPanel.setPosition( 0, yPosition );270271 // create and position Light AnimatedPanel272 elevatorLightPanel = new AnimatedPanel( 0, lightFrames );273 elevatorLightPanel.setPosition( OFFSET, 5 * OFFSET );274275 // create and position Bell AnimatedPanel276 bellPanel = new AnimatedPanel( 0, bellFrames );277278 yPosition = elevatorLightPanel.getPosition().getY() +279 elevatorLightPanel.getHeight() + OFFSET;280281 bellPanel.setPosition( OFFSET, yPosition );282 int bellRingAnimation[] = { 0, 1, 0, 2 };283 bellPanel.addFrameSequence( bellRingAnimation );

Fig. I.1 ElevatorView displays the elevator simulation model (part 6 of 18).

Page 7: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

Appendix I Elevator View (on CD) 1444

284285 // create and position Elevator's Button AnimatedPanel286 elevatorButtonPanel = 287 new AnimatedPanel( 0, elevatorButtonFrames );288289 yPosition = elevatorPanel.getHeight() - 6 * OFFSET;290 elevatorButtonPanel.setPosition( 10 * OFFSET, yPosition );291292 int buttonPressedFrameOrder[] = { 0, 1, 2 };293 elevatorButtonPanel.addFrameSequence( 294 buttonPressedFrameOrder );295296 // create List to store Person AnimatedPanels297 personAnimatedPanels = new ArrayList();298299 } // end method instantiatePanels300301 // place all Panels on ElevatorView302 private void placePanelsOnView()303 {304 // add Panels to ElevatorView305 add( firstFloorPanel );306 add( secondFloorPanel );307 add( ceilingPanel );308 add( elevatorPanel );309 add( firstFloorButtonPanel );310 add( secondFloorButtonPanel );311 add( firstFloorLightPanel );312 add( secondFloorLightPanel );313 add( elevatorShaftPanel );314 add( wallPanel );315316 // add Panels to Elevator's MovingPanel317 elevatorPanel.add( doorPanel );318 elevatorPanel.add( elevatorLightPanel );319 elevatorPanel.add( bellPanel );320 elevatorPanel.add( elevatorButtonPanel );321322 } // end method placePanelsOnView323324 // get sound effects and elevatorMusic325 private void initializeAudio()326 {327 // create AudioClip sound effects from audio files328 SoundEffects sounds = new SoundEffects();329 sounds.setPathPrefix( "sounds/" );330331 bellClip = sounds.getAudioClip( bellSound );332 doorOpenClip = sounds.getAudioClip( doorOpenSound );333 doorCloseClip = sounds.getAudioClip( doorCloseSound );334 elevatorClip = sounds.getAudioClip( elevatorSound );335 buttonClip = sounds.getAudioClip( buttonSound );336 walkClip = sounds.getAudioClip( walkingSound );

Fig. I.1 ElevatorView displays the elevator simulation model (part 7 of 18).

Page 8: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

1445 Elevator View (on CD) Appendix I

337338 // create MIDI player using Java Media Framework339 elevatorMusic = new ElevatorMusic( midiFile );340 elevatorMusic.open();341342 } // end method initializeAudio343344 // starts animation by repeatedly drawing images to screen345 public void startAnimation()346 {347 if ( animationTimer == null ) {348 animationTimer = 349 new javax.swing.Timer( ANIMATION_DELAY, this );350 animationTimer.start();351 }352 else353354 if ( !animationTimer.isRunning() )355 animationTimer.restart();356 }357358 // stop animation359 public void stopAnimation()360 {361 animationTimer.stop();362 }363364 // update AnimatedPanels animation in response to Timer365 public void actionPerformed( ActionEvent actionEvent )366 {367 elevatorPanel.animate();368369 firstFloorButtonPanel.animate();370 secondFloorButtonPanel.animate();371372 Iterator iterator = getPersonAnimatedPanelsIterator();373374 while ( iterator.hasNext() ) {375376 // get Person's AnimatedPanel from Set377 AnimatedPanel personPanel = 378 ( AnimatedPanel ) iterator.next();379380 personPanel.animate(); // update panel381 }382383 repaint(); // paint all Components384385 } // end method actionPerformed386387 private Iterator getPersonAnimatedPanelsIterator()388 {

Fig. I.1 ElevatorView displays the elevator simulation model (part 8 of 18).

Page 9: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

Appendix I Elevator View (on CD) 1446

389 // obtain iterator from List390 synchronized( personAnimatedPanels )391 {392 return new ArrayList( personAnimatedPanels ).iterator();393 }394 }395396 // stop sound clip of Person walking397 private void stopWalkingSound()398 {399 // stop playing walking sound400 walkClip.stop();401402 Iterator iterator = getPersonAnimatedPanelsIterator();403404 // but if Person is still walking, then keep playing405 while ( iterator.hasNext() ) {406 AnimatedPanel panel = ( AnimatedPanel ) iterator.next();407408 if ( panel.getXVelocity() != 0 )409 walkClip.loop();410 }411 } // end method stopWalkingSound412413 // returns Person AnimatedPanel with proper identifier414 private AnimatedPanel getPersonPanel( PersonMoveEvent event )415 {416 Iterator iterator = getPersonAnimatedPanelsIterator();417418 while ( iterator.hasNext() ) {419420 // get next AnimatedPanel421 AnimatedPanel personPanel = 422 ( AnimatedPanel ) iterator.next();423424 // return AnimatedPanel with identifier that matches425 if ( personPanel.getID() == event.getID() )426 return personPanel;427 }428429 // return null if no match with correct identifier430 return null;431432 } // end method getPersonPanel433434 // invoked when Elevator has departed from Floor435 public void elevatorDeparted( ElevatorMoveEvent moveEvent )436 {437 String location = 438 moveEvent.getLocation().getLocationName();439440 // determine if Person is on Elevator441 Iterator iterator = getPersonAnimatedPanelsIterator();

Fig. I.1 ElevatorView displays the elevator simulation model (part 9 of 18).

Page 10: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

1447 Elevator View (on CD) Appendix I

442443 while ( iterator.hasNext() ) {444445 AnimatedPanel personPanel =446 ( AnimatedPanel ) iterator.next();447448 double yPosition = personPanel.getPosition().getY();449 String panelLocation;450451 // determine on which Floor the Person entered452 if ( yPosition > secondFloorPosition )453 panelLocation = FIRST_FLOOR_NAME;454 else455 panelLocation = SECOND_FLOOR_NAME;456457 int xPosition = 458 ( int ) personPanel.getPosition().getX();459460 // if Person is inside Elevator461 if ( panelLocation.equals( location ) 462 && xPosition > PERSON_TO_BUTTON_DISTANCE + OFFSET ) {463464 // remove Person AnimatedPanel from ElevatorView465 remove( personPanel );466467 // add Person AnimatedPanel to Elevator468 elevatorPanel.add( personPanel, 1 );469 personPanel.setLocation( 2 * OFFSET, 9 * OFFSET );470 personPanel.setMoving( false );471 personPanel.setAnimating( false );472 personPanel.setVelocity( 0, 0 );473 personPanel.setCurrentFrame( 1 );474 }475 } // end while loop476477 // determine Elevator velocity depending on Floor478 if ( location.equals( FIRST_FLOOR_NAME ) )479 elevatorPanel.setVelocity( 0, -elevatorVelocity );480 else481482 if ( location.equals( SECOND_FLOOR_NAME ) )483 elevatorPanel.setVelocity( 0, elevatorVelocity );484485 // begin moving Elevator and play Elevator music486 elevatorPanel.setMoving( true );487488 if ( elevatorClip != null )489 elevatorClip.play();490491 elevatorMusic.play();492493 } // end method elevatorDeparted494

Fig. I.1 ElevatorView displays the elevator simulation model (part 10 of 18).

Page 11: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

Appendix I Elevator View (on CD) 1448

495 // invoked when Elevator has arrived at destination Floor496 public void elevatorArrived( ElevatorMoveEvent moveEvent )497 {498 // stop Elevator and music499 elevatorPanel.setMoving( false );500 elevatorMusic.getSequencer().stop();501502 double xPosition = elevatorPanel.getPosition().getX();503 double yPosition;504505 // set Elevator's position to either first or second Floor506 if ( elevatorPanel.getYVelocity() < 0 )507 yPosition = 508 secondFloorPosition - elevatorPanel.getHeight();509 else510 yPosition = 511 firstFloorPosition - elevatorPanel.getHeight();512513 elevatorPanel.setPosition( xPosition, yPosition );514515 } // end method elevatorArrived516517 // invoked when Person has been created in model518 public void personCreated( PersonMoveEvent personEvent )519 {520 int personID = personEvent.getID();521522 String floorLocation = 523 personEvent.getLocation().getLocationName();524525 // create AnimatedPanel representing Person526 AnimatedPanel personPanel = 527 new AnimatedPanel( personID, personFrames );528529 // determine where Person should be drawn initially530 // negative xPosition ensures Person drawn offscreen531 double xPosition = - personPanel.getWidth();532 double yPosition = 0;533534 if ( floorLocation.equals( FIRST_FLOOR_NAME ) )535 yPosition = firstFloorPosition +536 ( firstFloorPanel.getHeight() / 2 );537 else538539 if ( floorLocation.equals( SECOND_FLOOR_NAME ) )540 yPosition = secondFloorPosition + 541 ( secondFloorPanel.getHeight() / 2 );542543 yPosition -= personPanel.getHeight();544545 personPanel.setPosition( xPosition, yPosition );546

Fig. I.1 ElevatorView displays the elevator simulation model (part 11 of 18).

Page 12: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

1449 Elevator View (on CD) Appendix I

547 // add some animations for each Person548 int walkFrameOrder[] = { 1, 0, 1, 2 };549 int pressButtonFrameOrder[] = { 1, 3, 3, 4, 4, 1 };550 int walkAwayFrameOrder[] = { 6, 5, 6, 7 };551 personPanel.addFrameSequence( walkFrameOrder );552 personPanel.addFrameSequence( pressButtonFrameOrder );553 personPanel.addFrameSequence( walkAwayFrameOrder );554555 // have Person begin walking to Elevator556 personPanel.playAnimation( 0 );557 personPanel.setLoop( true );558 personPanel.setAnimating( true );559 personPanel.setMoving( true );560561 // determine Person velocity562 double time = 563 ( double ) ( TIME_TO_BUTTON / ANIMATION_DELAY );564565 double xDistance = PERSON_TO_BUTTON_DISTANCE - 566 2 * OFFSET + personPanel.getSize().width;567 double xVelocity = xDistance / time;568569 personPanel.setVelocity( xVelocity, 0 );570 personPanel.setAnimationRate( 1 );571572 walkClip.loop(); // play sound clip of Person walking573574 // store in personAnimatedPanels575 synchronized( personAnimatedPanels )576 {577 personAnimatedPanels.add( personPanel );578 }579580 add( personPanel, 0 );581582 } // end method personCreated583584 // invoked when Person has arrived at Elevator585 public void personArrived( PersonMoveEvent personEvent )586 {587 // find Panel associated with Person that issued event588 AnimatedPanel panel = getPersonPanel( personEvent );589590 if ( panel != null ) { // if Person exists591592 // Person stops at Floor Button593 panel.setMoving( false );594 panel.setAnimating( false );595 panel.setCurrentFrame( 1 );596 stopWalkingSound();597598 double xPosition = PERSON_TO_BUTTON_DISTANCE - 599 ( panel.getSize().width / 2 );

Fig. I.1 ElevatorView displays the elevator simulation model (part 12 of 18).

Page 13: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

Appendix I Elevator View (on CD) 1450

600 double yPosition = panel.getPosition().getY();601602 panel.setPosition( xPosition, yPosition );603 }604 } // end method personArrived605606 // invoked when Person has pressed Button607 public void personPressedButton( PersonMoveEvent personEvent )608 {609 // find Panel associated with Person that issued event610 AnimatedPanel panel = getPersonPanel( personEvent );611612 if ( panel != null ) { // if Person exists613614 // Person stops walking and presses Button615 panel.setLoop( false );616 panel.playAnimation( 1 );617618 panel.setVelocity( 0, 0 );619 panel.setMoving( false );620 panel.setAnimating( true );621 stopWalkingSound();622 }623 } // end method personPressedButton624625 // invoked when Person has started to enter Elevator626 public void personEntered( PersonMoveEvent personEvent )627 {628 // find Panel associated with Person that issued event629 AnimatedPanel panel = getPersonPanel( personEvent );630631 if ( panel != null ) {632633 // determine velocity634 double time = TIME_TO_ELEVATOR / ANIMATION_DELAY;635636 double distance = 637 elevatorPanel.getPosition().getX() - 638 panel.getPosition().getX() + 2 * OFFSET;639640 panel.setVelocity( distance / time, -1.5 );641642 // Person starts walking643 panel.setMoving( true );644 panel.playAnimation( 0 );645 panel.setLoop( true );646 }647 } // end method personEntered648649 // invoked when Person has departed from Elevator650 public void personDeparted( PersonMoveEvent personEvent)651 {

Fig. I.1 ElevatorView displays the elevator simulation model (part 13 of 18).

Page 14: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

1451 Elevator View (on CD) Appendix I

652 // find Panel associated with Person that issued event653 AnimatedPanel panel = getPersonPanel( personEvent );654655 if ( panel != null ) { // if Person exists656657 // determine velocity (in opposite direction)658 double time = TIME_TO_BUTTON / ANIMATION_DELAY;659 double xVelocity = - PERSON_TO_BUTTON_DISTANCE / time;660661 panel.setVelocity( xVelocity, 0 );662663 // remove Person from Elevator664 elevatorPanel.remove( panel );665666 double xPosition = 667 PERSON_TO_ELEVATOR_DISTANCE + 3 * OFFSET;668 double yPosition = 0;669670 String floorLocation = 671 personEvent.getLocation().getLocationName();672673 // determine Floor onto which Person exits674 if ( floorLocation.equals( FIRST_FLOOR_NAME ) )675 yPosition = firstFloorPosition +676 ( firstFloorPanel.getHeight() / 2 );677 else678679 if ( floorLocation.equals( SECOND_FLOOR_NAME ) )680 yPosition = secondFloorPosition + 681 ( secondFloorPanel.getHeight() / 2 );682683 yPosition -= panel.getHeight();684685 panel.setPosition( xPosition, yPosition );686687 // add Person to ElevatorView688 add( panel, 0 );689690 // Person starts walking691 panel.setMoving( true );692 panel.setAnimating( true );693 panel.playAnimation( 2 );694 panel.setLoop( true );695 walkClip.loop();696 }697 } // end method PersonDeparted698699 // invoked when Person has exited simulation700 public void personExited( PersonMoveEvent personEvent)701 {702 // find Panel associated with Person that issued moveEvent703 AnimatedPanel panel = getPersonPanel( personEvent );704

Fig. I.1 ElevatorView displays the elevator simulation model (part 14 of 18).

Page 15: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

Appendix I Elevator View (on CD) 1452

705 if ( panel != null ) { // if Person exists706707 panel.setMoving( false );708 panel.setAnimating( false );709710 // remove Person permanently and stop walking sound711 synchronized( personAnimatedPanels )712 {713 personAnimatedPanels.remove( panel );714 }715 remove( panel );716 stopWalkingSound();717 }718 } // end method personExited719720 // invoked when Door has opened in model721 public void doorOpened( DoorEvent doorEvent )722 {723 // get DoorEvent Location724 String location = 725 doorEvent.getLocation().getLocationName();726727 // play animation of Door opening728 doorPanel.playAnimation( 0 );729 doorPanel.setAnimationRate( 2 );730 doorPanel.setDisplayLastFrame( true );731732 // play sound clip of Door opening733 if ( doorOpenClip != null )734 doorOpenClip.play();735736 } // end method doorOpened737738 // invoked when Door has closed in model739 public void doorClosed( DoorEvent doorEvent )740 {741 // get DoorEvent Location742 String location = 743 doorEvent.getLocation().getLocationName();744745 // play animation of Door closing746 doorPanel.playAnimation( 1 );747 doorPanel.setAnimationRate( 2 );748 doorPanel.setDisplayLastFrame( true );749750 // play sound clip of Door closing751 if ( doorCloseClip != null )752 doorCloseClip.play();753754 } // end method doorClosed755

Fig. I.1 ElevatorView displays the elevator simulation model (part 15 of 18).

Page 16: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

1453 Elevator View (on CD) Appendix I

756 // invoked when Button has been pressed in model757 public void buttonPressed( ButtonEvent buttonEvent )758 {759 // get ButtonEvent Location760 String location = 761 buttonEvent.getLocation().getLocationName();762763 // press Elevator Button if from Elevator764 if ( location.equals( ELEVATOR_NAME ) ) {765 elevatorButtonPanel.playAnimation( 0 );766 elevatorButtonPanel.setDisplayLastFrame( true );767 }768769 // press Floor Button if from Floor770 else771772 if ( location.equals( FIRST_FLOOR_NAME ) ) {773 firstFloorButtonPanel.playAnimation( 0 );774 firstFloorButtonPanel.setDisplayLastFrame( true );775 }776 else777778 if ( location.equals( SECOND_FLOOR_NAME ) ) {779 secondFloorButtonPanel.playAnimation( 0 );780 secondFloorButtonPanel.setDisplayLastFrame( true );781 }782783 if ( buttonClip != null )784 buttonClip.play(); // play button press sound clip785786 } // end method buttonPressed787788 // invoked when Button has been reset in model789 public void buttonReset( ButtonEvent buttonEvent )790 {791 // get ButtonEvent Location792 String location = 793 buttonEvent.getLocation().getLocationName();794795 // reset Elevator Button if from Elevator796 if ( location.equals( ELEVATOR_NAME ) ) {797798 // return to first frame if still animating799 if ( elevatorButtonPanel.isAnimating() )800 elevatorButtonPanel.setDisplayLastFrame( false );801 else802 elevatorButtonPanel.setCurrentFrame( 0 );803 }804805 // reset Floor Button if from Floor806 else807

Fig. I.1 ElevatorView displays the elevator simulation model (part 16 of 18).

Page 17: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

Appendix I Elevator View (on CD) 1454

808 if ( location.equals( FIRST_FLOOR_NAME ) ) {809810 // return to first frame if still animating811 if ( firstFloorButtonPanel.isAnimating() )812 firstFloorButtonPanel.setDisplayLastFrame( 813 false );814 else815 firstFloorButtonPanel.setCurrentFrame( 0 );816 }817 else818819 if ( location.equals( SECOND_FLOOR_NAME ) ) {820821 // return to first frame if still animating822 if ( secondFloorButtonPanel.isAnimating() )823 secondFloorButtonPanel.setDisplayLastFrame( 824 false );825 else826 secondFloorButtonPanel.setCurrentFrame( 0 );827 }828829 } // end method buttonReset830831 // invoked when Bell has rung in model832 public void bellRang( BellEvent bellEvent )833 {834 bellPanel.playAnimation( 0 ); // animate Bell835836 if ( bellClip != null ) // play Bell sound clip837 bellClip.play();838 }839840 // invoked when Light turned on in model841 public void lightTurnedOn( LightEvent lightEvent )842 {843 // turn on Light in Elevator844 elevatorLightPanel.setCurrentFrame( 1 );845846 String location = 847 lightEvent.getLocation().getLocationName();848849 // turn on Light on either first or second Floor850 if ( location.equals( FIRST_FLOOR_NAME ) )851 firstFloorLightPanel.setCurrentFrame( 1 );852853 else854855 if ( location.equals( SECOND_FLOOR_NAME ) )856 secondFloorLightPanel.setCurrentFrame( 1 );857858 } // end method lightTurnedOn859

Fig. I.1 ElevatorView displays the elevator simulation model (part 17 of 18).

Page 18: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

1455 Elevator View (on CD) Appendix I

I.2 Class ObjectsThe ElevatorView is a JPanel with a series of other JPanel “children” added to it.Each JPanel provides a visual representation of an object from the model. For example,the ElevatorView contains ImagePanels, MovingPanels and AnimatedPan-els to represent the Elevator, Persons, the ElevatorShaft, the Buttons on theFloors, the Button in the Elevator, the Doors on the Floors, the Door in the El-evator, the Lights on the Floors, the two Floors and the Bell. Figure I.2 lists theElevatorView’s objects and their counterparts in the model.

860 // invoked when Light turned off in model861 public void lightTurnedOff( LightEvent lightEvent )862 {863 // turn off Light in Elevator864 elevatorLightPanel.setCurrentFrame( 0 );865866 String location = 867 lightEvent.getLocation().getLocationName();868869 // turn off Light on either first or second Floor870 if ( location.equals( FIRST_FLOOR_NAME ) )871 firstFloorLightPanel.setCurrentFrame( 0 );872873 else874875 if ( location.equals( SECOND_FLOOR_NAME ) )876 secondFloorLightPanel.setCurrentFrame( 0 );877878 } // end method lightTurnedOff879880 // return preferred size of ElevatorView881 public Dimension getPreferredSize()882 {883 return new Dimension( VIEW_WIDTH, VIEW_HEIGHT );884 }885886 // return minimum size of ElevatorView887 public Dimension getMinimumSize()888 {889 return getPreferredSize();890 }891892 // return maximum size of ElevatorView893 public Dimension getMaximumSize()894 {895 return getPreferredSize();896 }897 }

Fig. I.1 ElevatorView displays the elevator simulation model (part 18 of 18).

Page 19: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

Appendix I Elevator View (on CD) 1456

Lines 108–128 of class ElevatorView declare the objects in the second column ofFig. I.2. The firstFloorPanel (line 108), secondFloorPanel (line 109) andelevatorShaftPanel (line 110) are ImagePanels, because neither the Floors northe ElevatorShaft move in the simulation. The elevatorPanel (line 115) is aMovingPanel, because the Elevator’s only function is to move between Floors.The firstFloorButtonPanel (line 118), secondFloorButtonPanel (line119) and elevatorButtonPanel (line 120) are AnimatedPanels, because eachobject animates when the associated Button in the model is pressed or reset. The bell-Panel (line 121) is an AnimatedPanel to animate the ringing of the Bell. ThefirstFloorLightPanel (line 123) and secondFloorLightPanel (line 124) areAnimatedPanels, because these objects animate when the associated Light turns onor off. The doorPanel (line 125) is an AnimatedPanel to animate the opening andclosing of the Door. Note that the ElevatorView shows only the Door in the Ele-vator. The ElevatorView does not show the Doors on the Floors, which enablesus to show the Elevator’s interior (these Doors would obstruct the objects inside theElevator). Lastly, the personAnimatedPanels (line 128) is a List of Animat-edPanels, because there can exist several Person objects during execution—the Ele-vatorView must need to store dynamically the AnimatedPanels associated withPersons in the model.

We add to the ElevatorView three more elements that we assume to be parts of theElevator (Fig. I.3), although the model does not represent these elements—a light insidethe Elevator of type AnimatedPanel called elevatorLightPanel (line 122), aceiling over the Elevator of type ImagePanel called ceilingPanel (line 112),and wallpaper inside the building of type ImagePanel called wallPanel (line 111).

The object (in model) of Class...

is represented by the object (in view)... of Class...

Floor firstFloorPanelsecondFloorPanel

ImagePanelImagePanel

ElevatorShaft elevatorShaftPanel ImagePanel

Elevator elevatorPanel MovingPanel

Button (on Floor) firstFloorButtonPanelsecondFloorButtonPanel

AnimatedPanelAnimatedPanel

Button (in Elevator) elevatorButtonPanel AnimatedPanel

Bell bellPanel AnimatedPanel

Light firstFloorLightPanelsecondFloorLightPanel

AnimatedPanelAnimatedPanel

Door (in Elevator) doorPanel AnimatedPanel

Door (on Floor) <not represented> <not represented>

Person personAnimatedPanels List (of AnimatedPanels)

Fig. I.2 Objects in the ElevatorView representing objects in the model.

Page 20: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

1457 Elevator View (on CD) Appendix I

In addition, the class diagram of Fig. 22.9 shows that the ElevatorView containsone instance each of classes SoundEffects and ElevatorMusic. The SoundEf-fects object generates the AudioClips used to play sound effects, such as the Dooropening and a Person walking. Lines 131–136 declare all AudioClips, line 139declares the ElevatorMusic object, and line 328 (in method initializeAudio,which we discuss later in this section) declares the SoundEffects object.

I.3 Class ConstantsThe ElevatorView uses constants to specify or obtain such information as

• The initial placement of objects in the ElevatorView

• The rate at which the ElevatorView redraws the screen (animation rate)

• The names of image files used by the ImagePanels

• The names of sound files used by the SoundEffects object and the Eleva-torMusic

• The distances in pixels the ImagePanels representing the Elevator andPerson must travel

• The times needed to travel these distances

Lines 23–24 declare int constants VIEW_WIDTH and VIEW_HEIGHT, whichspecify the ElevatorView’s dimensions. Method getPreferredSize (lines 881–884) returns this dimension. Method pack of class ElevatorSimulation uses thismethod to obtain the ElevatorView’s dimension to place the ElevatorView in theGUI properly.

The ElevatorView has a null layout, so we may place ImagePanels in any x-y coordinate in the ElevatorView. Line 27 of class ElevatorView declares intconstant OFFSET, which helps to determine the exact positions of objects in the Eleva-torView. Line 30 declares int constant ANIMATION_DELAY, which specifies thenumber of milliseconds between animation frames. In our simulation, we initializeANIMATION_DELAY to 50 milliseconds. Lines 46–95 declare String constants speci-fying the image files used to instantiate the ImagePanels. Lines 98–105 declare theString constant specifying the audio files used to instantiate the AudioClips and theElevatorMusic.

Line 33 declares the int constant PERSON_TO_BUTTON_DISTANCE, which repre-sents the horizontal distance between the on-screen location of the firstFloorBut-

The object (in model) of Class...

is represented by the object (in view)... of Class...

<not represented> elevatorLightPanel AnimatedPanel

<not represented> ceilingPanel ImagePanel

<not represented> wallPanel ImagePanel

Fig. I.3 Objects in the ElevatorView not represented in the model.

Page 21: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

Appendix I Elevator View (on CD) 1458

tonPanel or secondFloorButtonPanel and the initial on-screen location of anAnimatedPanel associated with Person. This AnimatedPanel uses this constantto calculate the travel distance to the firstFloorButtonPanel or secondFloor-ButtonPanel. The firstFloorButtonPanel and secondFloorButton-Panel use the constant to position themselves on screen. Line 34 declares the intconstant BUTTON_TO_ELEVATOR_DISTANCE, describing the horizontal distancebetween the firstFloorButtonPanel or secondFloorButtonPanel and theelevatorPanel. The AnimatedPanel associated with a Person uses this constantto determine the travel distance when entering the elevatorPanel.

Line 39 declares int constant TIME_TO_BUTTON, which represents this Animat-edPanel’s travel time to the firstFloorButtonPanel or secondFloorBut-tonPanel. Line 40 declares int constant TIME_TO_ELEVATOR, which represents thetime the AnimatedPanel associated with a Person needs to enter the elevator-Panel from the firstFloorButtonPanel or secondFloorButtonPanel.Using the equation rate = distance / time, the AnimatedPanel associated with thePerson can determine the velocity needed to travel. Similarly, line 43 declares int con-stant ELEVATOR_TRAVEL_TIME, which represents the elevatorPanel’s travel timebetween the firstFloorPanel and secondFloorPanel—lines 166–169 use thisconstant to determine double attribute elevatorVelocity (line 149).

I.4 Class constructorThe responsibilities of the ElevatorView constructor (lines 152–174) are

• To instantiate all ImagePanels

• To add all ImagePanels to the ElevatorView

• To initialize the audio objects

• To compute the elevatorPanel’s initial velocity and distance traveled

• To start the animation Timer

Lines 157 calls private method instantiatePanels (lines 177–299), whichinstantiates all ImagePanels in the ElevatorView. Lines 180–181 instantiate thefirstFloorPanel and secondFloorPanel, and lines 184–190 set these objects’positions—the ElevatorView positions the firstFloorPanel on the bottom ofthe screen and positions the secondFloorPanel in the vertical center of the screen.Line 192 instantiates the wallPanel ImagePanel. The ElevatorView does notneed to calculate the position for the wallPanel, because the wallPanel’s defaultscreen position (i.e., xPosition = 0, yPosition = 0) is correct. Lines 195–202 andlines 205–210 instantiate and position the elevatorShaftPanel and ceiling-Panel ImagePanels, respectively. The ElevatorView positions the elevator-ShaftPanel in the right of the screen and positions the ceilingPanel above theelevatorShaftPanel. Lines 213–217 instantiate the elevatorPanel and posi-tion it over the elevatorShaftPanel above the firstFloorPanel. Lines 220–229 instantiate the firstFloorButtonPanel AnimatedPanel, place it next to theelevatorShaftPanel, then create a frame sequence Button pressed animation.Lines 232–240 perform the same actions on the secondFloorButtonPanel. Lines243–249 instantiate the firstFloorLightPanel AnimatedPanel and place it to

Page 22: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

1459 Elevator View (on CD) Appendix I

the left of the elevatorShaftPanel but above the firstFloorButtonPanel.Lines 251–256 position the secondFloorLightPanel above the secondFloor-ButtonPanel. Lines 259–269 instantiate the doorPanel AnimatedPanel, place itrelative to the elevatorPanel’s position (because the elevatorPanel will containthe doorPanel) and assign frame sequences describing the Door animation openingand closing. Lines 272–273 instantiate the elevatorLightPanel AnimatedPaneland position it over the elevatorPanel and to the left of the doorPanel. Lines 276–283 instantiate the bellPanel, position it below the elevatorLightPanel, thenassign a frame sequence describing the Bell ringing animation. Lines 286–294 instan-tiate the elevatorButtonPanel, position it in the center of the elevatorPaneland assign a frame sequence describing the Button pressed animation. Lastly, line 297instantiates the ArrayList holding the AnimatedPanels associated with the Per-sons in the model.

After the ElevatorView constructor has called method instantiatePanels,the constructor calls method placePanelsOnView (lines 302–322), which adds allinstantiated Panels to the ElevatorView. Lines 317–320 add the doorPanel, ele-vatorLightPanel, bellPanel and elevatorButtonPanel to the eleva-torPanel. The ElevatorView constructor then calls method initializeAudio(lines 325–342). Lines 328–329 instantiate a SoundEffects object, and lines 331–336use method getAudioClip of the SoundEffects object to return the AudioClipsfor the simulation. Method play of class AudioClip plays the AudioClip—the Ele-vatorView uses this method for sounds that do not repeat, such as the Bell ring.Method loop of class AudioClip plays the clip continually—the ElevatorViewuses this method for sounds that repeat, such as the sound of footsteps. Lines 339–340instantiate the ElevatorMusic object and ensure that the MIDI data is valid.

Finally, lines 162–163 (in the ElevatorView constructor) calculate the distancebetween the two Floors (i.e., the distance the elevatorPanel will travel). Lines 166–169 use the equation rate = distance / time to determine the elevatorPanel’s velocitywhen traveling. Finally, line 172 calls method startAnimation, which starts the ani-mation timer.

The ElevatorView animates the ImagePanels using animationTimer (line142), an instance of class javax.swing.Timer. The animationTimer starts in theElevatorView constructor through method startAnimation (lines 345–356). ClassElevatorView implements interface ActionListener to listen for ActionEvents.The animationTimer sends an ActionEvent to the ElevatorView every 50(ANIMATION_DELAY) milliseconds. When the ElevatorView receives an Action-Event, the ElevatorView calls method actionPerformed (lines 365–385). Line367 in this method update the position and current image of the elevatorPanel and ofthe elevatorPanel’s children. Lines 369–370 allow the firstFloorButtonPaneland secondFloorButtonPanel to update themselves. Lines 374–381 iterate ListpersonAnimatedPanels and update the position and current image of each Animat-edPanel associated with a Person in the model. Lastly, line 383 calls method repaintto redraw all ImagePanels added to the ElevatorView on screen.

We present an object diagram that lists all objects in the ElevatorView. Recall thatan object diagram provides a snapshot of the structure when the system is running. Theobject diagram of Fig. I.4 represents the ElevatorView after invoking the constructor.

Page 23: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

Appendix I Elevator View (on CD) 1460

The ElevatorView object links (contains an association) with all objects presentedin Fig. I.4. The elevatorPanel links with objects elevatorLightPanel, bell-Panel, doorPanel and elevatorButtonPanel. This association provides a visu-alization of what is happening in the model—the Elevator contains a Light, Bell,Door and Button. The SoundEffects object links with the AudioClip objects,because the SoundEffects object generates the AudioClip objects.

I.5 Event HandlingFigure 13.19 specified that the ElevatorView implements interface ElevatorMod-elListener, which implements all interfaces in the simulation. The ElevatorSim-ulation registers the ElevatorView as a listener for events from theElevatorModel; in other words, the ElevatorModel sends all events generated inthe model to the ElevatorView.

Every method implementing an interface receives an event object of type Eleva-torModelEvent (or a subclass) as a parameter. For example, the doorOpened method

Fig. I.4 Object diagram for the ElevatorView after initialization.

elevatorPanel : MovingPanel

firstFloorButtonPanel : AnimatedPanel

secondFloorButtonPanel : AnimatedPanel

elevatorButtonPanel : AnimatedPanel

doorPanel : AnimatedPanel

secondFloorLightPanel : AnimatedPanel

firstFloorLightPanel : AnimatedPanel

bellPanel : AnimatedPanel

elevatorShaftPanel : ImagePanel

secondFloorPanel : ImagePanel

lightPanel : AnimatedPanel

firstFloorPanel : ImagePanel

: SoundEffects

bellClip : AudioClip

doorOpenClip : AudioClip

doorCloseClip : AudioClip

elevatorClip : AudioClip

buttonClip : AudioClip

walkClip : AudioClip

ceilingPanel : ImagePanel

wallPanel : ImagePanel

: ElevatorView

: ElevatorMusic

Page 24: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

1461 Elevator View (on CD) Appendix I

receives a DoorEvent. Appendix G contains further reference on events and listeners.The following sections discuss the types of events that the ElevatorView handles.

I.5.1 ElevatorMoveEvent typesThe ElevatorModel sends an ElevatorMoveEvent when the Elevator has ei-ther departed or arrived in the model. The ElevatorModel invokes method eleva-torDeparted (lines 435–493) when the Elevator has departed from a Floor. Lines441–475 determine if an AnimatedPanel associated with a Person overlaps the el-evatorPanel by iterating personAnimatedPanels and testing whether any Ani-matedPanel in the List has an on-screen x-coordinate greater than that of theelevatorPanel. If this is the case, then the Person is inside the Elevator, and lines465–468 add the AnimatedPanel associated with that Person to the elevator-Panel. Regardless of whether a Person is inside the Elevator, lines 478–515 set theelevatorPanel’s velocity according to the direction the Elevator must travel. Line500 plays the elevatorMusic.

The ElevatorModel invokes method elevatorArrived (lines 496–515) whenthe Elevator has arrived at a Floor. Line 499 stops the elevatorPanel, and line512 stops the elevatorMusic. Lines 506–513 change the direction of the elevator-Panel for the next travel.

I.5.2 PersonMoveEvent typesThe ElevatorModel sends a PersonMoveEvent when a Person has performed someaction in the model that the ElevatorView must represent. The ElevatorModel in-vokes method personCreated (lines 518–582) when the model instantiates a new Per-son. Lines 526–527 instantiate an AnimatedPanel for a Person. Lines 531–545determine on which Floor to situate the AnimatedPanel, depending on the Floor onwhich the event was generated. Lines 548–553 add frame sequences to the AnimatedPan-el describing the Person walking and pressing a Button. Lines 556–572 animate thePerson walking, determine the Person’s velocity necessary to reach the Button on theFloor and play the sound effect of footsteps. Lastly, lines 575–580 add the Animated-Panel associated with the Person to List personAnimatedPanels, using a syn-chronized block (lines 575–578) to guarantee no other object can access the List.

The ElevatorModel invokes method personArrived (lines 585–604) when aPerson has arrived at the Elevator. Line 588 calls method getPersonPanel (lines414–432), which determines the AnimatedPanel associated with the Person thatissued the event. Specifically, method getPersonPanel iterates List personAni-matedPanels and returns the AnimatedPanel whose identifier matches the identifierof the PersonMoveEvent. Lines 590–603 in method personArrived stop this Ani-matedPanel from moving. Line 596 stops the sound of footsteps by calling methodstopWalkingSound (lines 397–411), which stops the AudioClip playing the foot-step sound only if no Persons are walking.

The ElevatorModel invokes method personPressedButton (lines 607–623)when a Person pressed a Button. Line 610 determines the AnimatedPanel associ-ated with the Person who pressed the Button. Line 616 calls method playAnima-tion, which plays the animation sequence of that Person pressing the Button.

Page 25: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

Appendix I Elevator View (on CD) 1462

The ElevatorModel invokes method personEntered (lines 626–647) when aPerson is about to enter the Elevator. Line 629 retrieves the AnimatedPanel asso-ciated with the Person entering the Elevator. Line 634–640 determine the velocityneeded to walk into the Elevator. Line 643–645 animate this AnimatedPanel towalk in the elevatorPanel.

The ElevatorModel invokes method personDeparted (lines 650–697) when aPerson is about to exit the Elevator. Line 653 determines the AnimatedPanelassociated with the Person departing from the Elevator. Lines 658–661 determine thatPerson’s velocity needed to walk to across the Floor to exit the simulation. Lines 664–688 position the AnimatedPanel associated with the Person on the Floor in front ofthe Elevator by removing the AnimatedPanel from the elevatorPanel andadding the AnimatedPanel to the ElevatorView. Lines 691–695 animate this Ani-matedPanel to walk across either the firstFloorPanel or secondFloorPaneland start the sound of footsteps.

The ElevatorModel invokes method personExited (lines 700–718) when aPerson has exited from the simulation. Line 703 determines the AnimatedPanel asso-ciated with the Person who exited the simulation. Lines 711–716 remove the Animat-edPanel associated with that Person from the ElevatorView and stop the sound offootsteps.

I.5.3 DoorEvent typesThe ElevatorModel sends a DoorEvent to the ElevatorView when a Door hasopened or closed in the model. The ElevatorModel invokes method doorOpened(lines 721–736) when a Door has opened. Lines 724–730 animate the doorPanel open-ing, and lines 733–734 plays the doorOpenClip, which is the sound effect associatedwith the Door’s opening.

The ElevatorModel invokes method doorClosed (lines 739–754) when aDoor has closed. Lines 742–748 animate the doorPanel closing, and lines 751–752plays the doorClosedClip, which is the sound effect associated with the Door’sclosing.

I.5.4 ButtonEvent typesThe ElevatorModel sends a ButtonEvent to the ElevatorView when a Buttonhas been pressed or reset in the model. The ElevatorModel invokes method button-Pressed (lines 757–786) when a Button has been pressed. Lines 760–761 determinethe Location where the Button was pressed. If the Location is the Elevator, thenlines 764–767 play the Button pressed animation inside the Elevator. If the Loca-tion is the first Floor, then lines 772–767 play the Button pressed animation on thefirst Floor. If the Location is the second Floor, then lines 778–781 play the Buttonpressed animation on the second Floor being pressed. Lines 783–784 play the button-Clip, which is the sound effect associated with the Button being pressed.

The ElevatorModel invokes method buttonReset (lines 789–829) when aButton has been reset. Lines 792–793 determine the Location where the Button wasreset. If the Location is the Elevator, then lines 796–803 change the elevator-ButtonPanel’s image to that of the Button reset. If the Location is the first Floor,

Page 26: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

1463 Elevator View (on CD) Appendix I

then lines 808–816 change the firstFloorButtonPanel’s image associated with theButton reset. If the Location is the second Floor, then lines 819–827 change thesecondFloorButtonPanel’s image associated with the Button reset.

I.5.5 BellEvent typesThe ElevatorModel sends a BellEvent to the ElevatorView by invoking meth-od bellRang (lines 832–838) when a Bell has rung in the model. Line 834 animates thebellPanel, and lines 836–837 play the bellClip, which is the sound effect associatedwith the Bell ringing.

I.5.6 LightEvent typesThe ElevatorModel sends a LightEvent to the ElevatorView when a Lighthas changed state in the model. The ElevatorModel invokes method light-TurnedOn (lines 841–858) when a Light has turned on. Line 844 turns on elevator-LightPanel. Lines 846–856 determine on which Floor the Light has turned on, thenilluminates the AnimatedPanel associated with that Light in the ElevatorView.

The ElevatorModel invokes method lightTurnedOff (lines 861–878) when aLight has turned off. Line 864 turns on elevatorLightPanel. Lines 866–876 deter-mine on which Floor the Light has turned on, then turns off the AnimatedPanelassociated with that Light in the ElevatorView.

I.6 Component Diagrams RevisitedIn Section 13.17, we introduced the component diagram for the elevator simulation, and inAppendix G and Appendix H, we added components to packages event and model, re-spectively. Figure I.5 presents the component diagram for package view, which containscomponents ElevatorView.java, ImagePanel.java, MovingPanel.java,AnimatedPanel.java, ElevatorMusic.java and SoundEffects.java.ElevatorView.java aggregates packages images, sounds and event. Packagesimages and sounds contain all image files and sound files (components) used by Ele-vatorView.java, respectively. The diagram does not show the components of these di-rectories, because there exist far to many graphics and audio files to represent on onepage—the contents of these packages can be found in the directory structures

com/deitel/jhtp4/elevator/view/imagescom/deitel/jhtp4/elevator/view/sounds

(i.e., in the images and sounds directory where the classes for the view are located inthe file system).

I.7 ConclusionCongratulations! You have completed an “industrial-strength” OOD/UML case study.

You are well prepared to tackle more substantial design problems and to go on to deeperstudy of OOD with the UML. Hopefully you have developed a greater appreciation andunderstanding of design and implementation processes. Now, you can use Java to imple-

Page 27: Elevator View (on CD) - Com Sci Gatecomscigate.com/java/htp4e/additional/append/jhtp4_appI.pdf · 2010. 10. 26. · 1439 Elevator View (on CD) Appendix I 22 // ElevatorView dimensions

Appendix I Elevator View (on CD) 1464

ment substantial object-oriented system designs generated by the UML. We hope you haveenjoyed using Java and the UML to construct this case study while learning what featuresthe two technologies have to offer. In addition, we hope you have enjoyed using Java’sGUI, graphics and sound capabilities, while learning important object-oriented and Java-related concepts, such as classes, objects, GUI construction, inheritance, event handlingand multithreading.

Fig. I.5 Component diagram for package view.

view

ElevatorView.java

<<file>>

ImagePanel.java

<<file>>

ElevatorMusic.java

<<file>>

AnimatedPanel.java

<<file>>

MovingPanel.java

<<file>>

SoundEffects.java

<<file>>

images sounds event

11 1

1

11