Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
154 views19 pages

IM Jhtp7 Ch21

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 19

21

Multimedia:
Applets and
The wheel that squeaks the
Applications
loudest … gets the grease.
—John Billings (Henry
Wheeler Shaw)

We’ll use a signal I have tried


OBJECTIVES
and found far-reaching and In this chapter you will learn:
easy to yell. Waa-hoo!
—Zane Grey ■ How to get, display and scale images.
■ How to create animations from sequences of images.
There is a natural hootchy- ■ How to create image maps.
kootchy motion to a goldfish.
—Walt Disney ■ How to get, play, loop and stop sounds, using an
AudioClip.
Between the motion and the ■ How to play video using interface Player.
act falls the shadow.
—Thomas Stearns Eliot

© 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:

1 // Exercise 21.6 Solution: Eraser.java


2 // Program slowly erases an image.
3 import java.awt.event.ActionListener;
4 import java.awt.event.ActionEvent;
5 import java.awt.Graphics;
6 import java.util.Random;
7 import javax.swing.ImageIcon;
8 import javax.swing.JApplet;
9 import javax.swing.Timer;
10
11 public class Eraser extends JApplet
12 {
13 private ImageIcon image;
14 private int imageWidth;
15 private int imageHeight;
16 private int count;
17 private int numberOfTimes;
18 private boolean showImage;
19 private Timer timer;
20
21 // initialize variables, start timer
22 public void init()
23 {
24 showImage = true;
25 count = 0;
26
27 image = new ImageIcon( "icons2.gif" ); // create ImageIcon
28 timer = new Timer( 1, new TimerHandler() ); // create Timer
29 timer.start(); // start Timer
30
31 imageWidth = image.getIconWidth();

© 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:

1 // Exercise 21.7 Solution: MyCanvasJPanel.java


2 // Program flashes text.
3 import java.awt.Color;
4 import java.awt.Dimension;
5 import java.awt.event.ActionListener;
6 import java.awt.event.ActionEvent;
7 import java.awt.Graphics;
8 import javax.swing.JPanel;
9 import javax.swing.Timer;
10
11 // creates the screen on which color and text flash
12 class MyCanvasJPanel extends JPanel
13 {
14 private String text; // text to be flashed onto screen
15 private Timer timer; // Timer used to flash at intervals
16 private Color color = Color.black; // set JPanel’s background color
17 boolean flash = true; // text should flash when program is run
18
19 // constructor
20 public MyCanvasJPanel()
21 {
22 setBackground( Color.black );
23 timer = new Timer( 150, new TimerHandler() );
24 timer.start(); // start timer
25 text = "Flash!"; // set text
26 setSize( 100, 100 ); // set size of JPanel
27 setOpaque( true ); // make JPanel opaque
28 } // end MyCanvasJPanel constructor
29
30 // draw text
31 public synchronized void paintComponent( Graphics g )
32 {
33 super.paintComponent( g );
34
35 if ( flash )
36 {
37 g.setColor( Color.yellow ); // set text color
38 g.drawString( text, 10, 20 ); // draw text
39 } // end if
40 } // end method paintComponent
41
42 // sets the flash rate
43 public void setSleepTime( int time )
44 {
45 // set delay time based on input, use 150 if invalid input entered

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
6 Chapter 21 Multimedia: Applets and Applications

46 timer.setDelay( time >= 50 && time <= 200 ? time : 150 );


47 } // end setSleepTime
48
49 // returns the current flash rate
50 public int getSleepTime()
51 {
52 return timer.getDelay();
53 } // end method getSleepTime
54
55 // used to size the window
56 public Dimension getPreferredSize()
57 {
58 return new Dimension( 100, 100 );
59 } // end method getPreferredSize
60
61 // inner class to handle action events from Timer
62 private class TimerHandler implements ActionListener
63 {
64 // respond to Timer's event
65 public void actionPerformed( ActionEvent actionEvent )
66 {
67 flash = !flash;
68 repaint(); // repaint animator
69 } // end method actionPerformed
70 } // end class TimerHandler
71 } // end class MyCanvasJPanel

1 // Exercise 21.7 Solution: Flash.java


2 // Program flashes text.
3 import java.awt.Color;
4 import java.awt.event.ActionListener;
5 import java.awt.event.ActionEvent;
6 import java.awt.event.ItemListener;
7 import java.awt.event.ItemEvent;
8 import java.awt.FlowLayout;
9 import javax.swing.JApplet;
10 import javax.swing.JComboBox;
11 import javax.swing.JLabel;
12 import javax.swing.JTextField;
13
14 public class Flash extends JApplet
15 {
16 private MyCanvasJPanel canvasJPanel;
17 private JComboBox colorJComboBox;
18 private JLabel inputJLabel;
19 private JTextField inputJTextField;
20
21 // initialize values and set up GUI
22 public void init()
23 {
24 // colors to set background to flash

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 7

25 String items[] = { "Black", "Red", "Blue", "Green" };


26
27 // create components
28 inputJLabel = new JLabel( "Enter rate ( 50 - 200 ):" );
29 inputJTextField = new JTextField( 5 );
30 inputJTextField.addActionListener(
31
32 new ActionListener() // anonymous inner class
33 {
34 public void actionPerformed( ActionEvent event )
35 {
36 // changes the rate at which the canvas flashes
37 canvasJPanel.setSleepTime(
38 Integer.parseInt( inputJTextField.getText() ) );
39 showStatus(
40 "Current Blink Rate: " + canvasJPanel.getSleepTime() );
41 } // end method actionPerformed
42 } // end anonymous inner class
43 ); // end call to addActionListener
44
45 canvasJPanel = new MyCanvasJPanel();
46 colorJComboBox = new JComboBox( items );
47 colorJComboBox.addItemListener(
48
49 new ItemListener() // anonymous inner class
50 {
51 // changes the background color based on selection
52 public void itemStateChanged( ItemEvent event )
53 {
54 Color color;
55
56 if ( event.getItem().equals( "Black" ) )
57 color = Color.black;
58 else if ( event.getItem().equals( "Red" ) )
59 color = Color.red;
60 else if ( event.getItem().equals( "Blue" ) )
61 color = Color.blue;
62 else
63 color = Color.green;
64
65 canvasJPanel.setBackground( color );
66 } // end method itemStateChanged
67 } // end anonymous inner class
68 ); // end call to addItemListener
69
70 // add components to container
71 setLayout( new FlowLayout() );
72
73 add( canvasJPanel );
74 add( colorJComboBox );
75 add( inputJLabel );
76 add( inputJTextField );
77 } // end method init
78 } // end class Flash

© 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:

1 // Exercise 21.8 Solution: Flash2JPanel.java


2 // Program flashes an image.
3 import java.awt.Color;
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.JPanel;
9 import javax.swing.Timer;
10
11 public class Flash2JPanel extends JPanel
12 {
13 private ImageIcon image;
14 private int imageWidth;
15 private int imageHeight;
16 private boolean flash;
17 private Timer timer;
18
19 // initialize variables, set background color, start timer
20 public Flash2JPanel()
21 {
22 flash = true;
23
24 image = new ImageIcon( "icons2.gif" );
25 imageWidth = image.getIconWidth();
26 imageHeight = image.getIconHeight();
27
28 // create and start Timer
29 timer = new Timer( 500, new TimerHandler() );
30 timer.start();
31 } // end Flash2JPanel constructor
32
33 // draw on JPanel

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 9

34 public void paintComponent( Graphics g )


35 {
36 super.paintComponent( g );
37
38 g.setColor( Color.BLUE );
39
40 // draw image
41 if ( flash == true )
42 image.paintIcon( this, g, 20, 20 );
43
44 // draw rectangle over image
45 else
46 g.fillRect( 20, 20, imageWidth, imageHeight );
47 } // end method paint
48
49 // inner class to handle action events from Timer
50 private class TimerHandler implements ActionListener
51 {
52 // respond to Timer's event
53 public void actionPerformed( ActionEvent actionEvent )
54 {
55 flash = !flash;
56 repaint(); // repaint animator
57 } // end method actionPerformed
58 } // end class TimerHandler
59 } // end class Flash2JPanel

1 // Exercise 21.8 Solution: Flash2.java


2 // Program flashes an image.
3 import javax.swing.JFrame;
4
5 public class Flash2
6 {
7 public static void main( String args[] )
8 {
9 Flash2JPanel flash2JPanel = new Flash2JPanel();
10 JFrame window = new JFrame( "Flashing Images" );
11 window.add( flash2JPanel );
12 window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
13 window.pack();
14 window.setSize( 380, 140 );
15 window.setVisible( true );
16 } // end main
17 } // end class Flash2

© 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:

1 // Exercise 21.9 Solution: DigitalClock.java


2 // Program creates a digital clock.
3 import java.awt.event.ActionListener;
4 import java.awt.event.ActionEvent;
5 import java.awt.Graphics;
6 import java.util.Date;
7 import javax.swing.JApplet;
8 import javax.swing.Timer;
9
10 public class DigitalClock extends JApplet
11 {
12 private String theTime;
13 private Timer timer;
14
15 // initialize variables
16 public void init()
17 {
18 theTime = "";
19 timer = new Timer( 1000, new TimerHandler() );
20 } // end method init
21
22 // draw on JApplet
23 public void paint( Graphics g )
24 {
25 super.paint( g ); // clears the background
26 g.drawString( theTime, 20, 50 );
27 } // end method paint
28
29 // start timer
30 public void start()
31 {
32 timer.start();
33 } // end method start
34
35 // stop timer
36 public void stop()
37 {
38 timer.stop();
39 } // end method stop

© 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:

1 // Exercise 21.10 Solution: MyCanvasJPanel.java


2 // Program highlights an image.
3 import java.awt.Color;
4 import java.awt.event.ActionListener;
5 import java.awt.event.ActionEvent;
6 import java.awt.Graphics;
7 import java.awt.Image;
8 import javax.swing.JPanel;
9 import javax.swing.Timer;
10
11 class MyCanvasJPanel extends JPanel
12 {
13 private Image image;
14 private Color[] lights;
15 private int numLights;
16 private int rows;
17 private int columns;
18 private int count;
19 private int bulbWidth;
20 private int bulbHeight;
21 private Timer timer;
22

© 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

1 // Exercise 21.10 Solution: Flash3.java


2 // Program highlights an image.
3 import java.awt.BorderLayout;
4 import java.awt.Image;
5 import javax.swing.ImageIcon;
6 import javax.swing.JApplet;
7
8 public class Flash3 extends JApplet
9 {
10 // MyCanvasJPanel displays a flashing border
11 private MyCanvasJPanel canvasJPanel;
12
13 // set up GUI to contain a MyCanvas
14 public void init()
15 {
16 // create an image icon
17 ImageIcon image = new ImageIcon( "icons2.gif" );
18
19 int width = image.getIconWidth();
20 int height = image.getIconHeight();
21
22 int wide = 12;
23 int high = 12;
24
25 // create canvas and add to GUI
26 canvasJPanel = new MyCanvasJPanel( image.getImage(),
27 width, height, wide, high );
28 add( canvasJPanel, BorderLayout.CENTER );
29 } // method init
30 } // end class Flash3

21.11 (Image Zooming) Create a program that enables you to zoom in on or out from an image.
ANS:

1 // Exercise 21.11 Solution: Zoom.java


2 // Program zooms an image.
3 import java.awt.BorderLayout;

© 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

Special Section: Challenging Multimedia Projects


The preceding exercises are keyed to the text and designed to test the reader’s understanding of fun-
damental multimedia concepts. This section includes a collection of advanced multimedia projects.
The reader should find these problems challenging, yet entertaining. The problems vary consider-
ably 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 exer-
cises.]
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 dis-
play 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 MemoryImage-
Source classes (see the Java API documentation for descriptions of these classes). You might try sev-
eral 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 im-
age.
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.
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.

© 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.

You might also like