Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Java How to Program, Fourth Edition - Deitel H., Deitel P.pdf
Скачиваний:
58
Добавлен:
24.05.2014
Размер:
14.17 Mб
Скачать

Chapter 18

Multimedia: Images, Animation, Audio and Video

1087

64 currentSound = sound1;

65

66 } // end method init

67

68// stop the sound when the user switches Web pages

69public void stop()

70{

71currentSound.stop();

72}

73

74// private inner class to handle button events

75private class ButtonHandler implements ActionListener {

77// process play, loop and stop button events

78public void actionPerformed( ActionEvent actionEvent )

79{

80

if ( actionEvent.getSource() == playSound )

81

currentSound.play();

82

 

83

else if ( actionEvent.getSource() == loopSound )

84

currentSound.loop();

85

 

86

else if ( actionEvent.getSource() == stopSound )

87

currentSound.stop();

88}

89}

90

91 } // end class LoadAudioAndPlay

Fig. 18.6 Loading and playing an AudioClip (part 3 of 3).

18.7 Internet and World Wide Web Resources

This section presents several Internet and Web resources for multimedia-related sites. (Additional resources are provided in Chapter 22.)

www.nasa.gov/gallery/index.html

The NASA multimedia gallery contains a wide variety of images, audio clips and video clips that you can download and use to test your Java multimedia programs.

sunsite.sut.ac.jp/multimed/

The Sunsite Japan Multimedia Collection also provides a wide variety of images, audio clips and video clips that you can download for educational purposes.

www.anbg.gov.au/anbg/index.html

The Australian National Botanic Gardens Web site provides links to sounds of many animals. Try, for example, the Common Birds link.

1088

Multimedia: Images, Animation, Audio and Video

Chapter 18

www.thefreesite.com

TheFreeSite.com has links to free sounds and clip art.

www.soundcentral.com

SoundCentral provides audio clips in WAV, AU, AIFF and MIDI formats.

www.animationfactory.com

The Animation Factory provides thousands of free GIF animations for personal use.

www.clipart.com

ClipArt.com contains links to Web sites that provide free art.

www.pngart.com

PNGART.com provides over 50,000 free images in PNG format, in an effort to help this newer image format gain popularity.

developer.java.sun.com/developer/techDocs/hi/repository

The Java Look-and-Feel Graphics Repository provides standard images for use in a Swing GUI.

SUMMARY

Applet method getImage loads an Image. One version of getImage takes two argu- ments—a location where the image is stored, and the file name of the image.

Applet method getDocumentBase returns the location of the applet’s HTML file on the Internet as an object of class URL (package java.net).

Java supports several image formats, including Graphics Interchange Format (GIF), Joint Photographic Experts Group (JPEG) and Portable Network Graphics (PNG). File names for each of these types end with .gif, .jpg (or .jpeg) or .png, respectively.

Class ImageIcon provides constructors that allow an ImageIcon object to be initialized with an image from the local computer or with an image stored on a Web server on the Internet.

Graphics method drawImage receives four arguments—a reference to the Image object in which the image is stored, the x- and y-coordinates where the image should be displayed and a reference to an ImageObserver object.

Another version of Graphics method drawImage outputs a scaled image. The fourth and fifth arguments specify the width and height of the image for display purposes.

Interface ImageObserver is implemented by class Component (an indirect superclass of Applet). ImageObservers are notified to update an image that was displayed as the remainder of the image is loaded.

ImageIcon method paintIcon displays the ImageIcon’s image. The method requires four arguments—a reference to the Component on which the image will be displayed, a reference to the Graphics object used to render the image, the x-coordinate of the upper-left corner of the image and the y-coordinate of the upper-left corner of the image.

Class ImageIcon’s paintIcon method does not allow scaling of an image. The class provides method getImage, which returns an Image reference that can be used with Graphics method drawImage to display a scaled version of an image.

Timer objects generate ActionEvents at fixed intervals in milliseconds and notify their registered ActionListeners that the events occurred. The Timer constructor receives two argu- ments—the delay in milliseconds and the ActionListener. Timer method start indicates that the Timer should start generating events. Timer method stop indicates that the Timer should stop generating events. Timer method restart indicates that the Timer should start generating events again.

Chapter 18

Multimedia: Images, Animation, Audio and Video

1089

Applets can be customized via parameters (the <param> tag) that are supplied from the HTML file that invokes the applet. The <param> tag lines must appear between the starting applet tag and the ending applet tag. Each parameter has a name and a value.

Applet method getParameter gets the value associated with a specific parameter and returns the value as a String. The argument passed to getParameter is a String containing the name of the parameter in the param tag. If there is no param tag containing the specified parameter, getParameter returns null.

An image map is an image that has hot areas that the user can click to accomplish a task, such as loading a different Web page into a browser.

Applet method play has two forms:

public void play( URL location, String soundFileName ); public void play( URL soundURL );

One version loads the audio clip stored in file soundFileName from location and plays the sound; the other takes a URL that contains the location and the file name of the audio clip.

Applet method getDocumentBase indicates the location of the HTML file that loaded the applet. Method getCodeBase indicates where the .class file for an applet is located.

The sound engine that plays audio clips supports several audio file formats, including Sun Audio file format (.au extension), Windows Wave file format (.wav extension), Macintosh AIFF file format (.aif or .aiff extension) and Musical Instrument Digital Interface (MIDI) file format (.mid or .rmi extensions). The Java Media Framework (JMF) supports other additional formats.

Applet method getAudioClip has two forms that take the same arguments as the play method. Method getAudioClip returns a reference to an AudioClip. AudioClips have three methods—play, loop and stop. Method play plays the audio once. Method loop continuously loops the audio clip. Method stop terminates an audio clip that is currently playing.

TERMINOLOGY

.aif file name extension

.aiff file name extension

.au file name extension

.gif file name extension

.jpeg file name extension

.jpg file name extension

.mid file name extension

.rmi file name extension

.wav file name extension animating a series of images animation

audio clip customize an applet

drawImage method of Graphics getAudioClip method of Applet getCodeBase method of Applet getDocumentBase method of Applet getHeight method of Component getIconHeight method of ImageIcon getIconWidth method of ImageIcon getImage method of Applet

getImage method of ImageIcon getParameter method of Applet getWidth method of Component graphics

Graphics Interchange Format (GIF) height of an image

hot area of an image map

Image class image map

ImageIcon class ImageObserver interface images

information button

Joint Photographic Experts Group (JPEG) loop method of interface AudioClip Macintosh AIFF file (.aif or .aiff) multimedia

Musical Instrument Digital Interface (MIDI) mute button

name attribute of param tag

paintIcon method of class ImageIcon

1090

Multimedia: Images, Animation, Audio and Video

Chapter 18

param tag

play method of class Applet

play method of interface AudioClip restart method of class Timer scaling an image

sound

sound engine space/time trade-off

start method of class Timer

stop method of class Timer

stop method of interface AudioClip Sun Audio file format (.au)

Timer class

update method of class Component value attribute of param tag volume control

width of an image Windows Wave file (.wav)

SELF-REVIEW EXERCISES

18.1Fill in the blanks in each of the following statements:

a)

Applet method

 

 

 

loads an image into an applet.

 

 

 

 

b)

Applet method

 

 

 

returns as an object of class URL the location on the Inter-

 

net of the HTML file that invoked the applet.

 

 

 

 

c)

Graphics method

 

 

 

displays an image on an applet.

 

 

 

 

d)

Java provides two mechanisms for playing sounds in an applet—the Applet’s play

 

method and the play method from the

 

 

interface.

 

 

 

 

e)

An

 

is an image that has hot areas that the user can click to accomplish a task

 

such as loading a different Web page.

 

 

 

 

 

 

 

f)

Method

 

 

 

 

of class ImageIcon displays the ImageIcon’s image.

 

g)

Java supports

several image formats,

including

,

 

and

 

 

.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

18.2State whether each of the following is true or false. If false, explain why.

a)A sound will be garbage collected as soon as it has finished playing.

b)Class ImageIcon provides constructors that allow an ImageIcon object to be initialized only with an image from the local computer.

c)Applet method getParameter gets the value associated with a specific HTML parameter and returns the value as a String.

ANSWERS TO SELF-REVIEW EXERCISES

18.1a) getImage. b) getDocumentBase. c) drawImage. d) AudioClip. e) image map. f) paintIcon. g) Graphics Interchange Format (GIF), Joint Photographic Experts Group (JPEG) Portable Network Graphics (PNG).

18.2a) False. The sound will be marked for garbage collection (if it is not referenced by an AudioClip) and will be garbage collected when the garbage collector is able to run. b) False. ImageIcon can load images from the Internet as well. c) True.

EXERCISES

18.3Describe how to make an animation “browser friendly.”

18.4Describe the Java methods for playing and manipulating audio clips.

18.5How can Java applets be customized with information from an HTML file?

18.6Explain how image maps are used. List 10 examples in which image maps are used.

18.7(Randomly Erasing an Image) Suppose an image is displayed in a rectangular screen area. One way to erase the image is simply to set every pixel to the same color immediately, but this is a dull visual effect. Write a Java program that displays an image and then erases it by using random-

Chapter 18

Multimedia: Images, Animation, Audio and Video

1091

number generation to select individual pixels to erase. After most of the image is erased, erase all of the remaining pixels at once. You can refer to individual pixels by having a line that starts and ends at the same point. You might try several variants of this problem. For example, you might display lines randomly or display shapes randomly to erase regions of the screen.

18.8(Text Flasher) Create a Java program that repeatedly flashes text on the screen. Do this by alternating the text with a plain background-color image. Allow the user to control the “blink speed” and the background color or pattern.

18.9(Image Flasher) Create a Java program that repeatedly flashes an image on the screen. Do this by alternating the image with a plain background-color image.

18.10(Digital Clock) Implement a program that displays a digital clock on the screen. You might add options to scale the clock; display day, month and year; issue an alarm; play certain audios at designated times and the like.

18.11(Calling Attention to an Image) If you want to emphasize an image, you might place a row of simulated light bulbs around your image. You can let the light bulbs flash in unison, or you can let them fire on and off in sequence one after the other.

18.12(Image Zooming) Create a program that enables you to zoom in on, or away from, an image.

SPECIAL SECTION: CHALLENGING MULTIMEDIA PROJECTS

The preceding exercises are keyed to the text and designed to test the reader’s understanding of fundamental multimedia concepts. This section includes a collection of advanced multimedia projects. The reader should find these problems challenging, yet entertaining. The problems vary considerably in difficulty. Some require an hour or two of program writing and implementation. Others are useful for lab assignments that might require two or three weeks of study and implementation. Some are challenging term projects. [Note: Solutions are not provided for these exercises.].

18.13(Animation) Create a a general purpose Java animation program. Your program should allow the user to specify the sequence of frames to be displayed, the speed at which the images are displayed, audios that should be played while the animation is running and so on.

18.14(Limericks) Modify the limerick-writing program you wrote in Exercise 10.10 to sing the limericks your program creates.

18.15(Random Inter-Image Transition) This provides a nice visual effect. If you are displaying one image in a given area on the screen and you would like to transition to another image in the same screen area, store the new screen image in an off-screen buffer and randomly copy pixels from the new image to the display area, overlaying the previous pixels at those locations. When the vast majority of the pixels have been copied, copy the entire new image to the display area to be sure you are displaying the complete new image. To implement this program, you may need to use the PixelGrabber and MemoryImageSource classes (see the Java API documentation for descriptions of these classes). You might try several variants of this problem. For example, try selecting all the pixels in a randomly selected straight line or shape in the new image, and overlay those pixels above the corresponding positions of the old image.

18.16(Background Audio) Add background audio to one of your favorite applications by using the loop method of class AudioClip to play the sound in the background while you interact with your application in the normal way.

18.17(Scrolling Marquee Sign) Create a Java program that scrolls dotted characters from right to left (or from left to right if that is appropriate for your language) across a Marquee-like display sign. As an option, display the text in a continuous loop, so that after the text disappears at one end it reappears at the other end.

1092

Multimedia: Images, Animation, Audio and Video

Chapter 18

18.18(Scrolling Image Marquee) Create a Java program that scrolls an image across a Marquee

screen.

18.19(Analog Clock) Create a Java program that displays an analog clock with hour, minute and second hands that move appropriately as the time changes.

18.20(Dynamic Audio and Graphical Kaleidoscope) Write a kaleidoscope program that displays reflected graphics to simulate the popular children’s toy. Incorporate audio effects that “mirror” your program’s dynamically changing graphics.

18.21(Automatic Jigsaw Puzzle Generator) Create a Java jigsaw puzzle generator and manipulator. Your user specifies an image. Your program loads and displays the image. Your program then breaks the image into randomly selected shapes and shuffles the shapes. The user then uses the mouse to move the puzzle pieces around to solve the puzzle. Add appropriate audio sounds as the pieces are being moved around and snapped back into place. You might keep tabs on each piece and where it really belongs and then use audio effects to help the user get the pieces into the correct positions.

18.22(Maze Generator and Walker) Develop a multimedia-based maze generator and traverser program based on the maze programs you wrote in Exercise 7.38–Exercise 7.40. Let the user customize the maze by specifying the number of rows and columns and by indicating the level of difficulty. Have an animated mouse walk the maze. Use audio to dramatize the movement of your mouse character.

18.23(One-Armed Bandit) Develop a multimedia simulation of a one-armed bandit. Have three spinning wheels. Place various fruits and symbols on each wheel. Use true random-number generation to simulate the spinning of each wheel and the stopping of each wheel on a symbol.

18.24(Horse Race) Create a Java simulation of a horse race. Have multiple contenders. Use audios for a race announcer. Play the appropriate audios to indicate the correct status of each of the contenders throughout the race. Use audios to announce the final results. You might try to simulate the kinds of horse-racing games that are often played at carnivals. The players get turns at the mouse and have to perform some skill-oriented manipulation with the mouse to advance their horses.

18.25(Shuffleboard) Develop a multimedia-based simulation of the game of shuffleboard. Use appropriate audio and visual effects.

18.26(Game of Pool) Create a multimedia-based simulation of the game of pool. Each player takes turns using the mouse to position a pool stick and to hit the stick against the ball at the appropriate angle to try to get the pool balls to fall into the pockets. Your program should keep score.

18.27(Artist) Design a Java art program that will give an artist a great variety of capabilities to draw, use images, use animations, etc., to create a dynamic multimedia art display.

18.28(Fireworks Designer) Create a Java program that someone might use to create a fireworks display. Create a variety of fireworks demonstrations. Then orchestrate the firing of the fireworks for maximum effect.

18.29(Floor Planner) Develop a Java program that will help someone arrange furniture in his or her home. Add features that enable the person to achieve the best possible arrangement.

18.30(Crossword) Crossword puzzles are among the most popular pastimes. Develop a multime- dia-based crossword-puzzle program. Your program should enable the player to place and erase words easily. Tie your program to a large computerized dictionary. Your program also should be able to suggest words based on which letters have already been filled in. Provide other features that will make the crossword-puzzle enthusiast’s job easier.

18.31(15 Puzzle) Write a multimedia-based Java program that enables the user to play the game of 15. There is a 4-by-4 board for a total of 16 slots. One of the slots is empty. The other slots are occupied by 15 tiles numbered 1 through 15. Any tile next to the currently empty slot can be moved into

Chapter 18

Multimedia: Images, Animation, Audio and Video

1093

that slot by clicking on the tile. Your program should create the board with the tiles out of order. The goal is to arrange the tiles into sequential order, row by row.

18.32(Reaction Time/Reaction Precision Tester) Create a Java program that moves a randomly created shape around the screen. The user moves the mouse to catch and click on the shape. The shape’s speed and size can be varied. Keep statistics on how much time the user typically takes to catch a shape of a given size. The user will probably have more difficulty catching faster moving, smaller shapes.

18.33(Calendar/Tickler File) Using both audio and images create a general purpose calendar and “tickler” file. For example, the program should sing “Happy Birthday” when you use it on your birthday. Have the program display images and play audios associated with important events. Also, have the program remind you in advance of these important events. It would be nice, for example, to have the program give you a week’s notice so you can pick up an appropriate greeting card for that special person.

18.34(Rotating Images) Create a Java program that lets you rotate an image through some number of degrees (out of a maximum of 360 degrees). The program should let you specify that you want to spin the image continuously. The program should let you adjust the spin speed dynamically.

18.35(Coloring Black and White Photographs and Images) Create a Java program that lets you paint a black and white photograph with color. Provide a color palette for selecting colors. Your program should let you apply different colors to different regions of the image.

18.36(Multimedia-Based Simpletron Simulator) Modify the Simpletron simulator that you developed in the exercises in the previous chapters to include multimedia features. Add computer-like sounds to indicate that the Simpletron is executing instructions. Add a breaking glass sound when a fatal error occurs. Use flashing lights to indicate which cells of memory and/or which registers are currently being manipulated. Use other multimedia techniques, as appropriate, to make your Simpletron simulator more valuable to its users as an educational tool.