IM Jhtp7 Ch21
IM Jhtp7 Ch21
IM Jhtp7 Ch21
Multimedia:
Applets and
The wheel that squeaks the
Applications
loudest … gets the grease.
—John Billings (Henry
Wheeler Shaw)
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
2 Chapter 21 Multimedia: Applets and Applications
Self-Review Exercises
21.1 Fill in the blanks in each of the following statements:
a) Applet method loads an image into an applet.
ANS: getImage
b) Graphics method displays an image on an applet.
ANS: drawImage
c) Java provides two mechanisms for playing sounds in an applet—the Applet’s play
method and the play method of the interface.
ANS: AudioClip
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.
ANS: image map
e) Method of class ImageIcon displays the ImageIcon’s image.
ANS: paintIcon
f) Java supports several image formats, including , and
.
ANS: Graphics Interchange Format (GIF), Joint Photographic Experts Group (JPEG),
Portable Network Graphics (PNG)
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.
ANS: True.
b) Class ImageIcon provides constructors that allow an ImageIcon object to be initialized
only with an image from the local computer.
ANS: False. ImageIcon can load images from the Internet as well.
c) Method play of class AudioClip continuously loops an audio clip.
ANS: False. Method play of class AudioClip plays an audio clip once. Method loop 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.
ANS: False. The Java 3D API is used for creating and modifying 3D graphics. The Java Im-
age I/O API is used for reading from and outputting images to files.
e) Applet method getDocumentBase returns, as an object of class URL, the location on the
Internet of the HTML file that invoked the applet.
ANS: True.
Exercises
21.3 Describe how to make an animation “browser friendly.”
ANS: Begin the animation with the start method of class Timer and suspend/terminate the
animation in the stop method of class Timer. The animation should stop when the
user switches web pages. If the user returns to the web page with the animation, the
animation should be restarted.
21.4 Describe the Java methods for playing and manipulating audio clips.
ANS: Class Applet method play and the AudioClip interface method play both load the
sound and play it once. AudioClip method loop continuously loops the audio clip in
the background. AudioClip method stop terminates an audio clip that is currently
playing.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 3
21.5 Explain how image maps are used. List several examples of their use.
ANS: Image maps are used to create interactive web pages that: a) load different web pages
based on user choice, b) show descriptive messages for images within the image maps,
c) define regions for an image, when the mouse enters the image region, display the
image, d) when the mouse clicks an image region, link the user to the URL associated
with the image.
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 of
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. [Note for Instructors: The solu-
tion to this exercise involves defining method paint, without making a call to the superclass’s paint
method. Each time paint is called, another pixel is erased. Alternately, students may store the pixels
to be erased and repeat the process of erasing these pixels each time paint is called (adding a pixel
to the list of stored pixels every millisecond). This solution, however, results in flickering. We sug-
gest the students use the first solution. Please inform the student of this.]
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
4 Chapter 21 Multimedia: Applets and Applications
32 imageHeight = image.getIconHeight();
33 numberOfTimes = imageWidth * imageHeight;
34 } // end method init
35
36 // draw on JApplet
37 public void paint( Graphics g )
38 {
39 Random random = new Random(); // get random number generator
40
41 // draw image only once
42 if ( showImage == true )
43 {
44 image.paintIcon( this, g, 0, 0 );
45 showImage = false;
46 } // end if
47
48 g.setColor( getBackground() );
49
50 // loop to increase speed
51 for ( int reps = 0; reps < 30; reps++ )
52 {
53 // generate random coordinates within image
54 int x = random.nextInt( imageWidth );
55 int y = random.nextInt( imageHeight );
56
57 g.drawLine( x, y, x, y ); // erase current pixel
58 } // end for
59
60 // erase remaining pixels when most of image has been erased
61 if ( count > numberOfTimes * .95 )
62 g.fillRect( 0, 0, imageWidth, imageHeight );
63
64 count += 30;
65 } // end method paint
66
67 // inner class to handle action events from Timer
68 private class TimerHandler implements ActionListener
69 {
70 // respond to Timer's event
71 public void actionPerformed( ActionEvent actionEvent )
72 {
73 repaint(); // call paint to erase image
74 } // end method actionPerformed
75 } // end class TimerHandler
76 } // end class Eraser
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 5
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 Action-
Events, respectively
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
6 Chapter 21 Multimedia: Applets and Applications
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 7
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
8 Chapter 21 Multimedia: Applets and Applications
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.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 9
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
10 Chapter 21 Multimedia: Applets and Applications
21.9 (Digital Clock) Implement a program that displays a digital clock on the screen.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 11
40
41 // inner class to handle action events from Timer
42 private class TimerHandler implements ActionListener
43 {
44 // respond to Timer's event
45 public void actionPerformed( ActionEvent actionEvent )
46 {
47 theTime = new Date().toString(); // get current date and time
48 repaint(); // repaint animator
49 } // end method actionPerformed
50 } // end class TimerHandler
51 } // end class DigitalClock
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.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
12 Chapter 21 Multimedia: Applets and Applications
23 // constructor
24 public MyCanvasJPanel( Image img,
25 int w, int h, int w2, int h2 )
26 {
27 int iconImageWidth = w; // width of icon image
28 int iconImageHeight = h; // height of icon image
29 bulbWidth = w2; // width of a bulb
30 bulbHeight = h2; // height of a bulb
31 image = img; // icon image
32
33 // create and start a timer
34 timer = new Timer( 300, new TimerHandler() );
35 timer.start();
36
37 // initialize values and create array
38 rows = iconImageWidth / bulbWidth + 2;
39 columns = iconImageHeight / bulbHeight;
40 numLights = 2 * rows + 2 * columns;
41 lights = new Color[ numLights ];
42
43 // used to make the lights blink
44 int count = 0;
45
46 setSize( bulbWidth * rows, bulbHeight * ( columns + 2 ) );
47 repaint();
48 } // end MyCanvasJPanel constructor
49
50 // override to produce blinking lights effect
51 public void paintComponent( Graphics g )
52 {
53 super.paintComponent( g );
54
55 // determine whether light is "on" or "off"
56 for ( int on = 0; on < numLights; on += 2 )
57 {
58 if ( count == 0 )
59 {
60 lights[ on ] = Color.YELLOW;
61 lights[ on + 1 ] = Color.WHITE;
62 } // end if
63 else
64 {
65 lights[ on ] = Color.WHITE;
66 lights[ on + 1 ] = Color.YELLOW;
67 } // end else
68 } // end for
69
70 // actually set position of light and draw
71 for ( int on = 0; on < numLights; on++ )
72 {
73 // reposition all lights
74 // top side, left to right
75 if ( on < rows )
76 drawBulb( g, lights[ on ], on * bulbWidth, 0 );
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 13
77
78 // right side, top to bottom
79 else if ( on >= rows && on < ( rows + columns ) )
80 drawBulb( g, lights[ on ], ( rows - 1 ) * bulbWidth,
81 ( on - rows + 1 ) * bulbHeight );
82
83 else if ( on >= ( rows + columns ) &&
84 on < ( rows * 2 + columns ) ) // bottom side, right to left
85 {
86 int xValue = rows - ( on - ( rows + columns ) ) - 1;
87
88 drawBulb( g, lights[ on ], xValue * bulbWidth,
89 ( columns + 1 ) * bulbHeight );
90 } // end else if
91 else // left side, bottom to top
92 {
93 int yValue =
94 columns - ( on - ( 2 * rows ) - columns );
95
96 drawBulb( g, lights[ on ], 0, yValue * bulbHeight );
97 } // end else
98 } // end for
99
100 g.drawImage( image, bulbWidth, bulbHeight,
101 bulbWidth * ( rows - 2 ), bulbHeight * columns, this );
102
103 // Change ++count to y to get the blinking effect
104 count = ++count % 2;
105 } // end method paintComponent
106
107 // draw light bulb on window
108 private void drawBulb(
109 Graphics graphics, Color fillColor, int x, int y )
110 {
111 graphics.setColor( Color.BLACK );
112 graphics.fillRect( x, y, bulbWidth, bulbHeight );
113
114 // fillColor determines if light is "on" or "off"
115 graphics.setColor( fillColor );
116 graphics.fillOval( x, y, 10, 10 );
117 } // end method drawBulb
118
119 // inner class to handle action events from Timer
120 private class TimerHandler implements ActionListener
121 {
122 // respond to Timer's event
123 public void actionPerformed( ActionEvent actionEvent )
124 {
125 repaint(); // repaint animator
126 } // end method actionPerformed
127 } // end class TimerHandler
128 } // end class MyCanvasJPanel
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
14 Chapter 21 Multimedia: Applets and Applications
21.11 (Image Zooming) Create a program that enables you to zoom in on or out from an image.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 15
4 import java.awt.event.ActionListener;
5 import java.awt.event.ActionEvent;
6 import java.awt.Graphics;
7 import javax.swing.ImageIcon;
8 import javax.swing.JApplet;
9 import javax.swing.JButton;
10 import javax.swing.JPanel;
11
12 public class Zoom extends JApplet
13 {
14 private ImageIcon image;
15 private JButton zoomInJButton;
16 private JButton zoomOutJButton;
17 private JPanel drawingJPanel;
18 private JPanel buttonJPanel;
19 private double imageWidth;
20 private double imageHeight;
21
22 // set up GUI, initialize variables
23 public void init()
24 {
25 image = new ImageIcon( "icons2.gif" );
26
27 // create buttons and add them to buttonJPanel
28 buttonJPanel = new JPanel();
29 zoomInJButton = new JButton( "Zoom In" ); // create Zoom In button
30 zoomInJButton.addActionListener(
31
32 new ActionListener() // anonymous inner class
33 {
34 public void actionPerformed( ActionEvent event )
35 {
36 // zoom in
37 imageWidth *= 2.0;
38 imageHeight *= 2.0;
39
40 // refresh image
41 repaint();
42 } // end method actionPerformed
43 } // end anonymous inner class
44 ); // end call to addActionListener
45
46 buttonJPanel.add( zoomInJButton );
47
48 // create Zoom Out button
49 zoomOutJButton = new JButton( "Zoom Out" );
50 zoomOutJButton.addActionListener(
51
52 new ActionListener() // anonymous inner class
53 {
54 public void actionPerformed( ActionEvent event )
55 {
56 // zoom out
57 imageWidth /= 2.0;
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
16 Chapter 21 Multimedia: Applets and Applications
58 imageHeight /= 2.0;
59
60 // refresh image
61 repaint();
62 } // end method actionPerformed
63 } // end anonymous inner class
64 ); // end call to addActionListener
65
66 buttonJPanel.add( zoomOutJButton );
67
68 imageWidth = image.getIconWidth();
69 imageHeight = image.getIconHeight();
70
71 drawingJPanel = new JPanel();
72 drawingJPanel.setSize( 800, 200 );
73
74 // add components to content pane
75 add( drawingJPanel, BorderLayout.CENTER );
76 add( buttonJPanel, BorderLayout.SOUTH );
77 } // end method init
78
79 // draw image with appropriate dimensions
80 public void paint( Graphics g )
81 {
82 super.paint( g );
83
84 g.drawImage( image.getImage(), 0, 0, ( int )imageWidth,
85 ( int )imageHeight, drawingJPanel );
86
87 buttonJPanel.repaint();
88 } // end method paint
89 } // end class Zoom
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Special Section: Challenging Multimedia Projects 17
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
18 Chapter 21 Multimedia: Applets and Applications
21.19 (Dynamic Audio and Graphical Kaleidoscope) Write a kaleidoscope program that displays re-
flected 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 random-
ly 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 belongs—then 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.20–Exercise 15.22. Let the user cus-
tomize the maze by specifying the number of rows and columns and by indicating the level of dif-
ficulty. 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-num-
ber 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 skill-oriented manipulation with it to advance their horses.
21.24 (Shuffleboard) Develop a multimedia-based simulation of the game of shuffleboard. Use ap-
propriate 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 dis-
play. 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 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 on which letters have already been filled in. Provide other features that will
make the crossword-puzzle enthusiast’s job easier.
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 or-
der. The goal is to arrange the tiles into sequential order, row by row.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Special Section: Challenging Multimedia Projects 19
21.31 (Reaction Time/Reaction Precision Tester) Create a Java program that moves a randomly cre-
ated 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” 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.
21.33 (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. It should let you adjust the spin speed dynamically.
21.34 (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.
21.35 (Multimedia-Based Simpletron Simulator) Modify the Simpletron simulator that you devel-
oped in the exercises in the previous chapters (Exercise 7.34–Exercise 7.36 and Exercise 17.26–
Exercise 17.30) to include multimedia features. Add computer-like sounds to indicate that the Sim-
pletron is executing instructions. Add a breaking-glass sound when a fatal error occurs. Use flashing
lights to indicate which cells of memory 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.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.