AhmadLang / Java, How To Program, 2004
.pdf
[Page 999 (continued)]
Summary
Applet method getImage loads an Image.
Applet method geTDocumentBase returns the location of the applet's HTML file on the Internet as an object of class URL.
Java supports several image formats, including Graphics Interchange Format (GIF), Joint
Photographic Experts Group (JPEG) and Portable Network Graphics (PNG). The file names for these types end with .gif, .jpg (or .jpeg) and .png, respectively.
Class ImageIcon provides constructors that allow an ImageIcon object to be initialized with an image from the local computer or stored on a Web server on the Internet.
Graphics method drawImage accepts four argumentsa 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. ImageObservers receive
notifications as an Image is loaded and update the image on the screen if it was not complete when it was displayed.
ImageIcon method paintIcon displays the ImageIcon's image. The method requires four
argumentsa 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.
A URL object represents a Uniform Resource Locator, which is as a pointer to a resource on the World Wide Web, on your computer or on any networked machine.
Timer objects generate ActionEvents at fixed intervals in milliseconds. The Timer constructor
receives two argumentsthe 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.
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:
[Page 1000]
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 version 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 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 methodsplay, loop and stop. Method play plays the audio clip once. Method loop continuously loops the audio clip. Method stop terminates an audio clip that is currently playing.
Sun Microsystems, Intel and Silicon Graphics worked together to produce the Java Media Framework (JMF)
Package javax.media and its subpackages contain the classes that compose the Java Media Framework.
Class Manager declares utility methods for accessing system resources to play and to manipulate media.
Method toURL of class File returns a URL that points to the File on the system.
[Page 1000 (continued)]
Terminology
.aif file extension
.aiff file extension
.au file extension
audio clip
AudioClip interface
.avi file extension
CannotRealizePlayerException exception createRealizedPlayer method of class Manager Dimension class
drawImage method of class Graphics
Future Splash (.spl) files getAudioClip method of class Applet getCodeBase method of class Applet
getControlPanelComponent method of interface Player geTDocumentBase method of class Applet
getImage method of class Applet getMinimumSize method of class Component getPreferredSize method of class Component getVisualComponent method of interface Player
.gif file extension
Graphics class
Graphics Interchange Format (GIF) hot area
Image class image map
ImageIcon class
ImageObserver interface
Java 3D API
Java Advanced Imaging API
Java Image I/O API
Java Media Framework (JMF) API
Java Sound API
Java Speech API javax.media package
Joint Photographic Experts Group (JPEG)
.jpeg file extension
.jpg file extension
LIGHTWEIGHT_RENDER constant of class Manager loop method of interface AudioClip
Macintosh AIFF file format (.aif or .aiff extension)
Macromedia Flash 2 movies (.swf)
Manager class
Microsoft Audio/Video Interleave (.avi) file
.mid file extension
.mov file extension
[Page 1001]
.mp3 file extension
.mpeg file extension
MPEG Layer 3 Audio (.mp3) files
MPEG-1 videos (.mpeg, .mpg)
.mpg file extension
multimedia
Musical Instrument Digital Interface (MIDI) file format (.mid or .rmi extension)
NoPlayerException exception
paintIcon method of class ImageIcon
play method of class Applet
play method of interface AudioClip Player interface
.png file extension
Portable Network Graphics (PNG) QuickTime (.mov) files
.rmi file extension
setHint method of class Manager showStatus method of class Applet sound
sound engine
.spl file extension
start method of interface Player stop method of class Timer
stop method of interface AudioClip
Sun Audio file format (.au extension)
.swf file extension
toURL method of class File URL class
video
.wav file extension
Windows Wave file format (.wav extension)
[Page 1001 (continued)]
Self-Review Exercises
21.1 Fill in the blanks in each of the following statements:
a.Applet method __________ loads an image into an applet.
b.Graphics method __________ displays an image on an applet.
c.Java provides two mechanisms for playing sounds in an appletthe Applet's play method and the play method of the __________ interface.
d.A(n) __________ is an image that has hot areas that the user can click to accomplish a task such as loading a Web page.
e.Method __________ of class ImageIcon displays the ImageIcon's image.
f.Java supports several image formats, including __________, __________ and
__________.
21.2 Determine whether each of the following statements is true or false. If false, explain why.
a.A sound is marked for garbage collection after it plays.
b.Class ImageIcon provides constructors that allow an ImageIcon object to be initialized only with an image from the local computer.
c.Method play of class AudioClip continuously loops an audio clip.
d.The Java Image I/O API is used for adding 3D graphics to a Java application.
e.Applet method geTDocumentBase returns, as an object of class URL, the location on the Internet of the HTML file that invoked the applet.
[Page 1001 (continued)]
Answers to Self-Review Exercises
21.1 a) getImage. b) drawImage. c) AudioClip. d) image map. e) paintIcon. f) Graphics Interchange Format (GIF), Joint Photographic Experts Group (JPEG), Portable Network Graphics (PNG).
21.2 a) True. b) False. ImageIcon can load images from the Internet as well. c) False. Method play of class AudioClip plays an audio clip once. Method loop of class AudioClip continuously loops an audio clip. d) False. The Java 3D API is used for creating and modifying 3D graphics. The Java Image I/O API is used for reading from and outputting images to files. e) True.
[Page 1001 (continued)]
Exercises
21.3Describe how to make an animation "browser friendly."
21.4Describe the Java methods for playing and manipulating audio clips.
[Page 1002]
21.5Explain how image maps are used. List several examples of their use.
21.6(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-number generation to select individual pixels to erase. After most of the image is erased, erase all the remaining pixels at once. You can draw individual pixels as a line that starts and ends at the same coordinates. 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.
21.7(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. You will need to use methods getDelay and setDelay of class Timer. These methods are used to retrieve and set the interval in milliseconds between ActionEvents, respectively
21.8(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.
21.9(Digital Clock) Implement a program that displays a digital clock on the screen.
21.10(Calling Attention to an Image) If you want to emphasize an image, you might place a row of simulated light bulbs around it. You can let the light bulbs flash in unison or fire on and off in sequence one after the other.
21.11(Image Zooming) Create a program that enables you to zoom in on or out from an image.
[Page 1002 (continued)]
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 to Instructors: Solutions are not provided for these exercises.].
21.12(Animation) Create a general-purpose Java animation program. It should allow the user to specify the sequence of frames to be displayed, the speed at which the images are displayed, audios to be played while the animation is running and so on.
21.13(Limericks) Modify the limerick-writing program you wrote in Exercise 10.10 to sing the limericks your program creates.
21.14(Random Interimage 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 area, store the new screen image in an off-screen buffer and randomly copy pixels from it to the display area, overlaying the pixels already 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 them above the corresponding positions of the old image.
21.15(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.
[Page 1003]
21.16(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.
21.17(Scrolling Image Marquee) Create a Java program that scrolls an image across a marquee screen.
21.18(Analog Clock) Create a Java program that displays an analog clock with hour, minute and second hands that move appropriately as the time changes.
21.19(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.
21.20(Automatic Jigsaw Puzzle Generator) Create a Java jigsaw puzzle generator and manipulator. The user specifies an image. Your program loads and displays the image, then breaks it into randomly selected shapes and shuffles them. The user then uses the mouse to move the pieces around to solve the puzzle. Add appropriate audio sounds as the pieces are moved around and snapped back into place. You might keep tabs on each piece and where it really belongsthen use audio effects to help the user
get the pieces into the correct positions.
21.21(Maze Generator and Walker) Develop a multimedia-based maze generator and traverser program based on the maze programs you wrote in Exercise 15.20Exercise 15.22. 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.
21.22(One-Armed Bandit)Develop a multimedia simulation of a "one-armed bandit." Have three spinning wheels. Place images of 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.
21.23(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 contender 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 take turns at the mouse and have to perform some skilloriented manipulation with it to advance their horses.
21.24(Shuffleboard) Develop a multimedia-based simulation of the game of shuffleboard. Use appropriate audio and visual effects.
21.25(Game of Pool) Create a multimedia-based simulation of the game of pool. Each player takes turns using the mouse to position a pool cue and hit it against the ball at the appropriate angle to try to make other balls fall into the pockets. Your program should keep score.
21.26(Artist) Design a Java art program that will give an artist a great variety of capabilities to draw, use images and use animations to create a dynamic multimedia art display.
21.27(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.
21.28(Floor Planner) Develop a Java program that will help someone arrange furniture in a home. Add features that enable the person to achieve the best possible arrangement.
21.29(Crossword) Crossword puzzles are among the most popular pastimes. Develop a multimedia-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 on which letters have already been filled in. Provide other features that will make the crossword-puzzle enthusiast's job easier.
[Page 1004]
21.30(15 Puzzle) Write a multimedia-based Java program that enables the user to play the game of 15. The game is played on a 4-by-4 board for a total of 16 slots. One slot is empty, the others are occupied by 15 tiles numbered 1 through 15. Any tile next to the currently empty slot can be moved into 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.
21.31(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.
21.32(Calendar/Tickler File) Using both audio and images, create a general-purpose calendar and "tickler" file. For example, the program should sing "Happy Birthday"
