 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 19 – Multimedia: Images, Animation and Audio Outline 19.1 Introduction 19.2 Loading, Displaying.

Slides:



Advertisements
Similar presentations
Computer Science 209 Images and GUIs. Working with Java Colors The class java.awt.Color includes constants, such as Color.red, for some commonly used.
Advertisements

Web Design & Development Lecture 19. Java Graphics 2.
Graphics You draw on a Graphics object The Graphics object cannot directly be created by your code, instead one is generated when the method paintComponent.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 15.1 Test-Driving the Craps Game Application.
1 L45 Multimedia: Applets and Applications. 2 OBJECTIVES  How to get and display images.  To create animations from sequences of images.  To create.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter Java Multimedia: Images, Animation, Audio.
Event Handling Events and Listeners Timers and Animation.
Lecture 24 Applets. Introduction to Applets Applets should NOT have main method but rather init, stop, paint etc They should be run through javac compiler.
1 Lecturte 14Lecture 7 Applications of Graphics Overview  Conversions Between Applications and Applets  Handling Mouse Events  Handling Keyboard Events.
Audio Chapter 17 - Student. (c) 2005 by Elizabeth Sugar Boese Audio Files Java can play the following audio types: .au (Sun Audio) .wav (Windows Wave)
 2000 Prentice Hall, Inc. All rights reserved. Java Multimedia: Images, Animation, Audio and Video Outline 30.1 Introduction 30.2Loading, Displaying and.
 Pearson Education, Inc. All rights reserved Multimedia: Applets and Applications.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L05 (Chapter 16) Applets.
Io package as Java’s basic I/O system continue’d.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 16 - Multimedia: Images, Animation, Audio and Video Outline 16.1 Introduction 16.2Downloading the.
Computer Science [3] Java Programming II - Laboratory Course Lab 7: Multimedia: Applets and Applications Faculty of Engineering & IT Software Engineering.
Java Programming, 2E Introductory Concepts and Techniques Chapter 2 Creating a Java Application and Applet.
Introduction Multimedia –Use of sound, image, graphics and video –Makes applications “come alive”
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 16.1 Test-Driving the Flag Quiz Application.
 2005 Pearson Education, Inc. All rights reserved Multimedia: Applets and Applications.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 18 – Multimedia: Images, Animation, Audio and Video Outline 18.1 Introduction 18.2 Loading, Displaying.
(c) 2008 E.S.Boese All Rights Reserved. Threads and Media Chapter 8 - Lecture Slides 1.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 20.1 Test-Driving the Screen Saver Application.
Chapter 17: Applets, Images, and Sound. Objectives Learn about applets Write an HTML document to host an applet Use the init() method Work with JApplet.
GUI programming Graphical user interface-based programming.
Timer Objects  regularly generates action events at programmer-specified time intervals  Timer class is in javax.swing package  Timer (int delay, ActionListener.
Lesson 34: Layering Images with Java GUI. The FlowLayout RECAP.
 2002 Prentice Hall, Inc. All rights reserved Introduction Graphical User Interface (GUI) –Gives program distinctive “look” and “feel” –Provides.
 2000 Prentice Hall, Inc. All rights reserved. Java Multimedia: Images, Animation, Audio and Video Outline 30.1 Introduction 30.2Loading, Displaying and.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 16 Applets and Multimedia.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 19.1 Test-Driving the Shipping Hub Application.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Review of Graphics in Java,
Lesson 39: More wrapup on GUIs. 1.This presentation will focus on the decisions around software architecture and the decisions that will drive the code.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
Java Programming Working with Sound and Images. Topics Learn about the paint() and repaint() methods Learn about paintComponent() method Use the drawString()
Introduction Multimedia –Use of sound, image, graphics and video –Makes applications “come alive”
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Intro to Applets. Applet Applets run within the Web browser environment Applets bring dynamic interaction and live animation to an otherwise static HTML.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 2 – Welcome Application Introduction to Graphical.
Creating a Java Application and Applet
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 27.1 Test-Driving the Drawing Shapes Application.
Introduction to Applets Chapter 21. Applets An applet is a Java application that is intended to be invoked and executed through a Web browser. Click Here.
1 Layout Managers Layout managers –Provided for arranging GUI components –Provide basic layout capabilities –Processes layout details –Programmer can concentrate.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 10.
1/18H212Mouse and Timer Events H212 Introduction to Software Systems Honors Lecture #16: Mouse and Timer Events October 26, 2015.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 17.1 Test-Driving the Student Grades Application.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Lesson 28: More on the GUI button, frame and actions.
Lesson 33: Layout management and drawing – Java GUI.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 28.1 Java Speech API 28.2 Downloading and.
Mouse, Keyboard, Sounds, and Images JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 7 Event-Driven Programming and Basic GUI Objects.
Chapter 14 Applets and More. 2 Contents I. Introduction to Applets II. A Brief Introduction to HTML III. Creating Applets with Swing IV. Using AWT for.
Introduction to Graphics
Lecture 09 Applets.
Multimedia in Java Multimedia combines graphics, animation and sound
Advanced GUIs and Graphics
Presentation transcript:

 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 19 – Multimedia: Images, Animation and Audio Outline 19.1 Introduction 19.2 Loading, Displaying and Scaling Images 19.3 Animating a Series of Images 19.4 Image Maps 19.5 Loading and Playing Audio Clips 19.6 Internet and World Wide Web Resources 19.7 (Optional Case Study) Thinking About Objects: Animation and Sound in the View

 2003 Prentice Hall, Inc. All rights reserved Introduction Multimedia –Use of sound, image, graphics and video –Makes applications “come alive”

 2003 Prentice Hall, Inc. All rights reserved Introduction (cont.) This chapter focuses on –Image-manipulation basics –Creating smooth animations –Playing audio files (via AudioClip interface) –Creating image maps

 2003 Prentice Hall, Inc. All rights reserved Loading, Displaying and Scaling Images Demonstrate some Java multimedia capabilities –java.awt.Image abstract class (cannot be instantiated) Can represent several image file formats –e.g., GIF, JPEG and PNG –javax.swing.ImageIcon Concrete class

 2003 Prentice Hall, Inc. All rights reserved. Outline LoadImageAndSca le.java Line 15 Line 16 Line 22 Line 25 1 // Fig. 19.1: LoadImageAndScale.java 2 // Load an image and display it in its original size and twice its 3 // original size. Load and display the same image as an ImageIcon. 4 import java.applet.Applet; 5 import java.awt.*; 6 import javax.swing.*; 7 8 public class LoadImageAndScale extends JApplet { 9 private Image logo1; 10 private ImageIcon logo2; // load image when applet is loaded 13 public void init() 14 { 15 logo1 = getImage( getDocumentBase(), "logo.gif" ); 16 logo2 = new ImageIcon( "logo.gif" ); 17 } // display image 20 public void paint( Graphics g ) 21 { 22 g.drawImage( logo1, 0, 0, this ); // draw original image // draw image to fit the width and the height less 120 pixels 25 g.drawImage( logo1, 0, 120, getWidth(), getHeight() - 120, this ); Objects of class Image must be created via method getImage Objects of class ImageIcon may be created via ImageIcon constructor Method drawImage displays Image object on screen Overloaded method drawImage displays scaled Image object on screen

 2003 Prentice Hall, Inc. All rights reserved. Outline LoadImageAndSca le.java Line 28 Program Output // draw icon using its paintIcon method 28 logo2.paintIcon( this, g, 180, 0 ); 29 } } // end class LoadImageAndScale Method paintIcon displays ImageIcon object on screen

 2003 Prentice Hall, Inc. All rights reserved Animating a Series of Images Demonstrate animating series of images –Images are stored in array

 2003 Prentice Hall, Inc. All rights reserved. Outline LogoAnimator.ja va Line 23 Lines 26 and 28 1 // Fig. 19.2: LogoAnimator.java 2 // Animation of a series of images. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class LogoAnimator extends JPanel implements ActionListener { 8 9 private final static String IMAGE_NAME = "deitel"; // base image name 10 protected ImageIcon images[]; // array of images private int totalImages = 30; // number of images 13 private int currentImage = 0; // current image index 14 private int animationDelay = 50; // millisecond delay 15 private int width; // image width 16 private int height; // image height private Timer animationTimer; // Timer drives animation // initialize LogoAnimator by loading images 21 public LogoAnimator() 22 { 23 images = new ImageIcon[ totalImages ]; // load images 26 for ( int count = 0; count < images.length; ++count ) 27 images[ count ] = new ImageIcon( getClass().getResource( 28 "images/" + IMAGE_NAME + count + ".gif" ) ); Create array that stores series of ImageIcon objects Load ImageIcon objects into array

 2003 Prentice Hall, Inc. All rights reserved. Outline LogoAnimator.ja va Lines Lines // this example assumes all images have the same width and height 31 width = images[ 0 ].getIconWidth(); // get icon width 32 height = images[ 0 ].getIconHeight(); // get icon height 33 } // display current image 36 public void paintComponent( Graphics g ) 37 { 38 super.paintComponent( g ); images[ currentImage ].paintIcon( this, g, 0, 0 ); // move to next image only if timer is running 43 if ( animationTimer.isRunning() ) 44 currentImage = ( currentImage + 1 ) % totalImages; 45 } // respond to Timer's event 48 public void actionPerformed( ActionEvent actionEvent ) 49 { 50 repaint(); // repaint animator 51 } // start or restart animation 54 public void startAnimation() 55 { Override method paintComponent of class JPanel to display ImageIcon s Timer invokes method actionPerformed every animationDelay ( 50 ) milliseconds

 2003 Prentice Hall, Inc. All rights reserved. Outline LogoAnimator.ja va Line if ( animationTimer == null ) { 57 currentImage = 0; 58 animationTimer = new Timer( animationDelay, this ); 59 animationTimer.start(); 60 } 61 else // continue from last image displayed 62 if ( ! animationTimer.isRunning() ) 63 animationTimer.restart(); 64 } // stop animation timer 67 public void stopAnimation() 68 { 69 animationTimer.stop(); 70 } // return minimum size of animation 73 public Dimension getMinimumSize() 74 { 75 return getPreferredSize(); 76 } // return preferred size of animation 79 public Dimension getPreferredSize() 80 { 81 return new Dimension( width, height ); 82 } 83 Method stop indicates that Timer should stop generating events

 2003 Prentice Hall, Inc. All rights reserved. Outline LogoAnimator.ja va 84 // execute animation in a JFrame 85 public static void main( String args[] ) 86 { 87 LogoAnimator animation = new LogoAnimator(); // create LogoAnimator JFrame window = new JFrame( "Animator test" ); // set up window 90 window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); Container container = window.getContentPane(); 93 container.add( animation ); window.pack(); // make window just large enough for its GUI 96 window.setVisible( true ); // display window 97 animation.startAnimation(); // begin animation } // end method main } // end class LogoAnimator

 2003 Prentice Hall, Inc. All rights reserved Image Maps Image map –Contains hot areas Message appears when user moves cursor over these areas

 2003 Prentice Hall, Inc. All rights reserved. Outline ImageMap.java Lines // Fig. 19.3: ImageMap.java 2 // Demonstrating an image map. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class ImageMap extends JApplet { 8 private ImageIcon mapImage; 9 10 private static final String captions[] = { "Common Programming Error", 11 "Good Programming Practice", "Graphical User Interface Tip", 12 "Performance Tip", "Portability Tip", 13 "Software Engineering Observation", "Error-Prevention Tip" }; // set up mouse listeners 16 public void init() 17 { 18 addMouseListener( new MouseAdapter() { // anonymous inner class // indicate when mouse pointer exits applet area 23 public void mouseExited( MouseEvent event ) 24 { 25 showStatus( "Pointer outside applet" ); 26 } } // end anonymous inner class ); // end call to addMouseListener Add MouseListener for when mouse pointer exits applet area

 2003 Prentice Hall, Inc. All rights reserved. Outline ImageMap.java Lines Lines addMouseMotionListener( new MouseMotionAdapter() { // anonymous inner class // determine icon over which mouse appears 37 public void mouseMoved( MouseEvent event ) 38 { 39 showStatus( translateLocation( 40 event.getX(), event.getY() ) ); 41 } } // end anonymous inner class ); // end call to addMouseMotionListener mapImage = new ImageIcon( "icons.png" ); // get image } // end method init // display mapImage 52 public void paint( Graphics g ) 53 { 54 super.paint( g ); 55 mapImage.paintIcon( this, g, 0, 0 ); 56 } 57 Add MouseMotionListener for hot areas

 2003 Prentice Hall, Inc. All rights reserved. Outline ImageMap.java Line // return tip caption based on mouse coordinates 59 public String translateLocation( int x, int y ) 60 { 61 // if coordinates outside image, return immediately 62 if ( x >= mapImage.getIconWidth() || y >= mapImage.getIconHeight() ) 63 return ""; // determine icon number (0 - 6) 66 int iconWidth = mapImage.getIconWidth() / 7; 67 int iconNumber = x / iconWidth; return captions[ iconNumber ]; // return appropriate icon caption 70 } } // end class ImageMap Test coordinates to determine the icon over which the mouse was positioned

 2003 Prentice Hall, Inc. All rights reserved. Outline ImageMap.java Program Output

 2003 Prentice Hall, Inc. All rights reserved. Outline ImageMap.java Program Output

 2003 Prentice Hall, Inc. All rights reserved Loading and Playing Audio Clips Playing audio clips –Method play of class Applet –Method play of class AudioClip –Java’s sound engine Supports several audio file formats –Sun Audio (.au ) –Windows Wave (.wav ) –Macintosh AIFF (.aif or.aiff ) –Musical Instrument Digital Interface (MIDI) (.mid )

 2003 Prentice Hall, Inc. All rights reserved. Outline LoadAudioAndPla y.java Line 10 1 // Fig. 19.4: LoadAudioAndPlay.java 2 // Load an audio clip and play it. 3 4 import java.applet.*; 5 import java.awt.*; 6 import java.awt.event.*; 7 import javax.swing.*; 8 9 public class LoadAudioAndPlay extends JApplet { 10 private AudioClip sound1, sound2, currentSound; 11 private JButton playSound, loopSound, stopSound; 12 private JComboBox chooseSound; // load the image when the applet begins executing 15 public void init() 16 { 17 Container container = getContentPane(); 18 container.setLayout( new FlowLayout() ); String choices[] = { "Welcome", "Hi" }; 21 chooseSound = new JComboBox( choices ); chooseSound.addItemListener( new ItemListener() { 26 Declare three AudioClip objects

 2003 Prentice Hall, Inc. All rights reserved. Outline LoadAudioAndPla y.java Lines // stop sound and change to sound to user's selection 28 public void itemStateChanged( ItemEvent e ) 29 { 30 currentSound.stop(); currentSound = 33 chooseSound.getSelectedIndex() == 0 ? sound1 : sound2; 34 } } // end anonymous inner class ); // end addItemListener method call container.add( chooseSound ); // set up button event handler and buttons 43 ButtonHandler handler = new ButtonHandler(); playSound = new JButton( "Play" ); 46 playSound.addActionListener( handler ); 47 container.add( playSound ); loopSound = new JButton( "Loop" ); 50 loopSound.addActionListener( handler ); 51 container.add( loopSound );

 2003 Prentice Hall, Inc. All rights reserved. Outline LoadAudioAndPla y.java Lines stopSound = new JButton( "Stop" ); 54 stopSound.addActionListener( handler ); 55 container.add( stopSound ); // load sounds and set currentSound 58 sound1 = getAudioClip( getDocumentBase(), "welcome.wav" ); 59 sound2 = getAudioClip( getDocumentBase(), "hi.au" ); 60 currentSound = sound1; } // end method init // stop the sound when the user switches Web pages 65 public void stop() 66 { 67 currentSound.stop(); 68 } // private inner class to handle button events 71 private class ButtonHandler implements ActionListener { 72 Method getAudioClip loads audio file into AudioClip object

 2003 Prentice Hall, Inc. All rights reserved. Outline LoadAudioAndPla y.java Line 77 Line 80 Line // process play, loop and stop button events 74 public void actionPerformed( ActionEvent actionEvent ) 75 { 76 if ( actionEvent.getSource() == playSound ) 77 currentSound.play(); else if ( actionEvent.getSource() == loopSound ) 80 currentSound.loop(); else if ( actionEvent.getSource() == stopSound ) 83 currentSound.stop(); 84 } } // end class ButtonHandler } // end class LoadAudioAndPlay Method stop stops playing the audio clip Method play starts playing the audio clip Method loops plays the audio clip continually

 2003 Prentice Hall, Inc. All rights reserved (Optional Case Study) Thinking About Objects: Animation and Sound in the View ImagePanel –Used for objects that are stationary in model e.g., Floor, ElevatorShaft MovingPanel –Used for objects that “move” in model e.g., Elevator AnimatedPanel –Used for objects that “animate” in model e.g., Person, Door, Button, Bell, Light

 2003 Prentice Hall, Inc. All rights reserved (Optional Case Study) Thinking About Objects: Animation and Sound in the View (cont.) Fig 19.5 Class diagram of elevator simulation view. 1 MovingPanel AnimatedPanel 1 SoundEffects 1 1..* 1 1 ElevatorView ImagePanel javax.swing.JPanel graphics view audio

 2003 Prentice Hall, Inc. All rights reserved. Outline ImagePanel.java Line 13 Line 16 Line 19 Line 25 1 // ImagePanel.java 2 // JPanel subclass for positioning and displaying ImageIcon 3 package com.deitel.jhtp5.elevator.view; 4 5 // Java core packages 6 import java.awt.*; 7 import java.awt.geom.*; 8 import java.util.*; 9 10 // Java extension packages 11 import javax.swing.*; public class ImagePanel extends JPanel { // identifier 16 private int ID; // on-screen position 19 private Point2D.Double position; // imageIcon to paint on screen 22 private ImageIcon imageIcon; // stores all ImagePanel children 25 private Set panelChildren; 26 ImagePanel extends JPanel, so ImagePanel can be displayed on screen Each ImagePanel has a unique identifier Point2D.Double offers precision for x-y position coordinate Set of ImagePanel children

 2003 Prentice Hall, Inc. All rights reserved. Outline ImagePanel.java Lines // constructor initializes position and image 28 public ImagePanel( int identifier, String imageName ) 29 { 30 super( null ); // specify null layout 31 setOpaque( false ); // make transparent // set unique identifier 34 ID = identifier; // set location 37 position = new Point2D.Double( 0, 0 ); 38 setLocation( 0, 0 ); // create ImageIcon with given imageName 41 imageIcon = new ImageIcon( 42 getClass().getResource( imageName ) ); Image image = imageIcon.getImage(); 45 setSize( 46 image.getWidth( this ), image.getHeight( this ) ); // create Set to store Panel children 49 panelChildren = new HashSet(); } // end ImagePanel constructor 52 Use imageName argument to instantiate ImageIcon that will be displayed on screen

 2003 Prentice Hall, Inc. All rights reserved. Outline ImagePanel.java Lines Lines Lines // paint Panel to screen 54 public void paintComponent( Graphics g ) 55 { 56 super.paintComponent( g ); // if image is ready, paint it to screen 59 imageIcon.paintIcon( this, g, 0, 0 ); 60 } // add ImagePanel child to ImagePanel 63 public void add( ImagePanel panel ) 64 { 65 panelChildren.add( panel ); 66 super.add( panel ); 67 } // add ImagePanel child to ImagePanel at given index 70 public void add( ImagePanel panel, int index ) 71 { 72 panelChildren.add( panel ); 73 super.add( panel, index ); 74 } 75 Display ImagePanel (and its ImageIcon ) to screen Override method add to add ImagePanel child Overload method add to add ImagePanel child

 2003 Prentice Hall, Inc. All rights reserved. Outline ImagePanel.java Lines // remove ImagePanel child from ImagePanel 77 public void remove( ImagePanel panel ) 78 { 79 panelChildren.remove( panel ); 80 super.remove( panel ); 81 } // sets current ImageIcon to be displayed 84 public void setIcon( ImageIcon icon ) 85 { 86 imageIcon = icon; 87 } // set on-screen position 90 public void setPosition( double x, double y ) 91 { 92 position.setLocation( x, y ); 93 setLocation( ( int ) x, ( int ) y ); 94 } // return ImagePanel identifier 97 public int getID() 98 { 99 return ID; 100 } 101 Override method remove to remove ImagePanel child

 2003 Prentice Hall, Inc. All rights reserved. Outline ImagePanel.java Lines // get position of ImagePanel 103 public Point2D.Double getPosition() 104 { 105 return position; 106 } // get imageIcon 109 public ImageIcon getImageIcon() 110 { 111 return imageIcon; 112 } // get Set of ImagePanel children 115 public Set getChildren() 116 { 117 return panelChildren; 118 } 119 } Accessor methods

 2003 Prentice Hall, Inc. All rights reserved. Outline MovingPanel.jav a Line 13 Lines // MovingPanel.java 2 // JPanel subclass with on-screen moving capabilities 3 package com.deitel.jhtp5.elevator.view; 4 5 // Java core packages 6 import java.awt.*; 7 import java.awt.geom.*; 8 import java.util.*; 9 10 // Java extension packages 11 import javax.swing.*; public class MovingPanel extends ImagePanel { // should MovingPanel change position? 16 private boolean moving; // number of pixels MovingPanel moves in both x and y values 19 // per animationDelay milliseconds 20 private double xVelocity; 21 private double yVelocity; // constructor initializes position, velocity and image 24 public MovingPanel( int identifier, String imageName ) 25 { 26 super( identifier, imageName ); 27 MovingPanel represents moving object in model Use double to represent velocity with high-precision

 2003 Prentice Hall, Inc. All rights reserved. Outline MovingPanel.jav a Lines // set MovingPanel velocity 29 xVelocity = 0; 30 yVelocity = 0; } // end MovingPanel constructor // update MovingPanel position and animation frame 35 public void animate() 36 { 37 // update position according to MovingPanel velocity 38 if ( isMoving() ) { 39 double oldXPosition = getPosition().getX(); 40 double oldYPosition = getPosition().getY(); setPosition( oldXPosition + xVelocity, 43 oldYPosition + yVelocity ); 44 } // update all children of MovingPanel 47 Iterator iterator = getChildren().iterator(); while ( iterator.hasNext() ) { 50 MovingPanel panel = ( MovingPanel ) iterator.next(); 51 panel.animate(); 52 } 53 } // end method animate // is MovingPanel moving on screen? 56 public boolean isMoving() 57 { 58 return moving; 59 } 60 If MovingPanel is moving, update MovingPanel position, as well as position of MovingPanel ’s children

 2003 Prentice Hall, Inc. All rights reserved. Outline MovingPanel.jav a Lines // set MovingPanel to move on screen 62 public void setMoving( boolean move ) 63 { 64 moving = move; 65 } // set MovingPanel x and y velocity 68 public void setVelocity( double x, double y ) 69 { 70 xVelocity = x; 71 yVelocity = y; 72 } // return MovingPanel x velocity 75 public double getXVelocity() 76 { 77 return xVelocity; 78 } // return MovingPanel y velocity 81 public double getYVelocity() 82 { 83 return yVelocity; 84 } 85 }

 2003 Prentice Hall, Inc. All rights reserved. Outline AnimatedPanel.j ava Line 12 Lines Line 23 Lines // AnimatedPanel.java 2 // MovingPanel subclass with animation capabilities 3 package com.deitel.jhtp5.elevator.view; 4 5 // Java core packages 6 import java.awt.*; 7 import java.util.*; 8 9 // Java extension packages 10 import javax.swing.*; public class AnimatedPanel extends MovingPanel { // should ImageIcon cycle frames 15 private boolean animating; // frame cycle rate (i.e., rate advancing to next frame) 18 private int animationRate; 19 private int animationRateCounter; 20 private boolean cycleForward = true; // individual ImageIcons used for animation frames 23 private ImageIcon imageIcons[]; // storage for all frame sequences 26 private java.util.List frameSequences; 27 private int currentAnimation; AnimatedPanel represents moving object in model and has several frames of animation Variables to determine which frame of animation to display ImageIcon array that stores images in an animation sequence Variables to control animation rate

 2003 Prentice Hall, Inc. All rights reserved. Outline AnimatedPanel.j ava Lines Lines // should loop (continue) animation at end of cycle? 30 private boolean loop; // should animation display last frame at end of animation? 33 private boolean displayLastFrame; // helps determine next displayed frame 36 private int currentFrameCounter; // constructor takes array of filenames and screen position 39 public AnimatedPanel( int identifier, String imageName[] ) 40 { 41 super( identifier, imageName[ 0 ] ); // creates ImageIcon objects from imageName string array 44 imageIcons = new ImageIcon[ imageName.length ]; for ( int i = 0; i < imageIcons.length; i++ ) { 47 imageIcons[ i ] = new ImageIcon( 48 getClass().getResource( imageName[ i ] ) ); 49 } frameSequences = new ArrayList(); } // end AnimatedPanel constructor // update icon position and animation frame 56 public void animate() 57 { 58 super.animate(); AnimatedPanel constructor creates ImageIcon array from String array argument, which contains names of image files Override method animate of class MovingPanel to update AnimatedPanel position and current frame of animation

 2003 Prentice Hall, Inc. All rights reserved. Outline AnimatedPanel.j ava Lines Lines Lines // play next animation frame if counter > animation rate 61 if ( frameSequences != null && isAnimating() ) { if ( animationRateCounter > animationRate ) { 64 animationRateCounter = 0; 65 determineNextFrame(); 66 } 67 else 68 animationRateCounter++; 69 } 70 } // end method animate // determine next animation frame 73 private void determineNextFrame() 74 { 75 int frameSequence[] = 76 ( int[] ) frameSequences.get( currentAnimation ); // if no more animation frames, determine final frame, 79 // unless loop is specified 80 if ( currentFrameCounter >= frameSequence.length ) { 81 currentFrameCounter = 0; // if loop is false, terminate animation 84 if ( !isLoop() ) { setAnimating( false ); 87 Play next frame of animation Utility method that determines next frame of animation to display Used for looping purposes in animation: If loop is false, animation terminates after one iteration

 2003 Prentice Hall, Inc. All rights reserved. Outline AnimatedPanel.j ava Lines Lines if ( isDisplayLastFrame() ) // display last frame in sequence 91 currentFrameCounter = frameSequence.length - 1; 92 } 93 } // set current animation frame 96 setCurrentFrame( frameSequence[ currentFrameCounter ] ); 97 currentFrameCounter++; } // end method determineNextFrame // add frame sequence (animation) to frameSequences ArrayList 102 public void addFrameSequence( int frameSequence[] ) 103 { 104 frameSequences.add( frameSequence ); 105 } // ask if AnimatedPanel is animating (cycling frames) 108 public boolean isAnimating() 109 { 110 return animating; 111 } // set AnimatedPanel to animate 114 public void setAnimating( boolean animate ) 115 { 116 animating = animate; 117 } Call method setCurrent- Frame to set ImageIcon (current image displayed) to the ImageIcon returned from the current frame sequence. Last frame in sequence is displayed if displayLastFrame is true, and first frame in sequence is displayed if displayLastFrame is false

 2003 Prentice Hall, Inc. All rights reserved. Outline AnimatedPanel.j ava // set current ImageIcon 120 public void setCurrentFrame( int frame ) 121 { 122 setIcon( imageIcons[ frame ] ); 123 } // set animation rate 126 public void setAnimationRate( int rate ) 127 { 128 animationRate = rate; 129 } // get animation rate 132 public int getAnimationRate() 133 { 134 return animationRate; 135 } // set whether animation should loop 138 public void setLoop( boolean loopAnimation ) 139 { 140 loop = loopAnimation; 141 } // get whether animation should loop 144 public boolean isLoop() 145 { 146 return loop; 147 } 148

 2003 Prentice Hall, Inc. All rights reserved. Outline AnimatedPanel.j ava Lines // get whether to display last frame at animation end 150 private boolean isDisplayLastFrame() 151 { 152 return displayLastFrame; 153 } // set whether to display last frame at animation end 156 public void setDisplayLastFrame( boolean displayFrame ) 157 { 158 displayLastFrame = displayFrame; 159 } // start playing animation sequence of given index 162 public void playAnimation( int frameSequence ) 163 { 164 currentAnimation = frameSequence; 165 currentFrameCounter = 0; 166 setAnimating( true ); 167 } 168 } Begin animation

 2003 Prentice Hall, Inc. All rights reserved (Optional Case Study) Thinking About Objects: Animation and Sound in the View (Cont.) Fig Relationship between array imageIcons and List frameSequences = 1= 2= 3= frameSequences A C D imageIcons B B A C A B B A D C B A D C C A image sequences

 2003 Prentice Hall, Inc. All rights reserved. Outline SoundEffects.ja va Line 8 Lines // SoundEffects.java 2 // Returns AudioClip objects 3 package com.deitel.jhtp5.elevator.view; 4 5 // Java core packages 6 import java.applet.*; 7 8 public class SoundEffects { 9 10 // location of sound files 11 private String prefix = ""; public SoundEffects() {} // get AudioClip associated with soundFile 16 public AudioClip getAudioClip( String soundFile ) 17 { 18 try { 19 return Applet.newAudioClip( getClass().getResource( 20 prefix + soundFile ) ); 21 } // return null if soundFile does not exist 24 catch ( NullPointerException nullPointerException ) { 25 return null; 26 } 27 } Pass soundFile parameter to static method newAudioClip (of class java.applet.Applet ) to return AudioClip object Creates sound effects ( AudioClip s) for view

 2003 Prentice Hall, Inc. All rights reserved. Outline SoundEffects.ja va // set prefix for location of soundFile 30 public void setPathPrefix( String string ) 31 { 32 prefix = string; 33 } 34 }