Download Java Multimedia: Images, Animation, Audio and Video

Document related concepts
no text concepts found
Transcript
Chapter 16 - Multimedia: Images,
Animation, Audio and Video
Outline
16.1
16.2
16.3
16.4
16.5
16.6
16.7
16.8
16.9
16.10
16.11
Introduction
Downloading the Java Media Framework
Loading, Displaying and Scaling Images
Loading and Playing Audio Clips
The Java Media Player
Animating a Series of Images
Animation Issues
Customizing Applets via the HTML param Tag
Image Maps
Java Plug-In
Internet and World Wide Web Resources
 2000 Prentice Hall, Inc. All rights reserved.
16.1 Introduction
• Revolution in computer industry
– Before, computers used for high-speed calculations
– Now, data manipulation important
• Multimedia
– "Sizzle" of Java - images, sound, video
– CDs, DVDs, video cards
– Demands extraordinary computing power
• Fast processors making multimedia possible
• Java
– Built-in multimedia capabilities
• Most programming languages do not
– Develop powerful multimedia applications
 2000 Prentice Hall, Inc. All rights reserved.
16.2 Downloading the Java Media
Framework
• Java media framework (JMF)
–
–
–
–
Extension to Java API
Enhanced processing of images, audio, and video
Constantly evolving
Some examples required the JMF, not included in J2SDK
http://java.sun.com/products/java-media/jmf/1.1/
• JMF Downloads for Windows and Solaris
– At time of writing, early versions of JMF 2.0 available
http://java.sun.com/products/java-media/jmf/index.html
 2000 Prentice Hall, Inc. All rights reserved.
16.2 Loading, Displaying and Scaling
Images
• Java Multimedia
– Discuss graphics, images, animations, sounds, and video
– Begin with images
• Class Image (java.awt)
– Abstract class, cannot create an object directly
• Request Image be loaded and returned
– getImage( imageLocation, filename );
• Of class Applet (superclass of JApplet)
• imageLocation
– getDocumentBase() is URL (address) of HTML file
• filename - .gif or .jpg (.jpeg)
10
16
private Image logo1;
logo1 = getImage( getDocumentBase(), "logo.gif" );
 2000 Prentice Hall, Inc. All rights reserved.
16.2 Loading, Displaying and Scaling
Images
• Displaying Images
– Method drawImage (class Graphics)
– Many overloaded versions
g.drawImage( myImage, x, y, ImageObserver );
• myImage - Image object
• x,y - coordinates to display image
• ImageObserver - object on which image is displayed
– Use "this" to indicate the applet
– Can be any object that implements ImageObserver
interface
24
g.drawImage( logo1, 0, 0, this );
 2000 Prentice Hall, Inc. All rights reserved.
16.2 Loading, Displaying and Scaling
Images
• Displaying Images
– g.drawImage( myImage, x, y, width, height,
ImageObserver );
• width and height
– Dimensions of image (automatically scaled)
• getWidth(), getHeight()
– Returns dimensions of applet
28
g.drawImage( logo1, 0, 120,
29
 2000 Prentice Hall, Inc. All rights reserved.
getWidth(), getHeight() - 120, this );
16.2 Loading, Displaying and Scaling
Images
• Class ImageIcon
– Concrete class (can create objects)
– Example constructor and initialization
11
17
private ImageIcon logo2;
logo2 = new ImageIcon( "logo.gif" );
• Displaying Icons
– Method paintIcon (class Graphics)
myIcon.paintIcon( Component, Graphics, x, y )
• Component - Component object on which to display
image (this)
• Graphics - Graphics object used to render image (g)
• x, y - coordinates of Icon
 2000 Prentice Hall, Inc. All rights reserved.
16.2 Loading, Displaying and Scaling
Images
• Usage
– ImageIcons simpler than Images
• Create objects directly
• No need for ImageObserver reference
– All components are ImageObservers
– Cannot scale ImageIcons
• Scaling
– Use ImageIcon method getImage
• Returns Image reference
• This can be used with drawImage and scaled
 2000 Prentice Hall, Inc. All rights reserved.
1// Fig. 16.1: LoadImageAndScale.java
Outline
2// Load an image and display it in its original size
3// and scale it to twice its original width and height.
4// Load and display the same image as an ImageIcon.
5import java.applet.Applet;
6import java.awt.*;
1. Declare objects
7import javax.swing.*;
8
2. init()
9public class LoadImageAndScale extends JApplet {
10
private Image logo1;
Notice the parameters to the
11
private ImageIcon logo2;
constructors. Image objects
cannot objects
2.1 Initialize
12
be created directly.
13
// load the image when the applet is loaded
14
public void init()
3. paint()
15
{
16
logo1 = getImage( getDocumentBase(), "logo.gif" );
3.1 drawImage
17
logo2 = new ImageIcon( "logo.gif" );
18
}
19
20
// display the image
drawImage calls (second
21
public void paint( Graphics g )
22
{
call has scaling). this
23
// draw the original image
means the image will be
24
g.drawImage( logo1, 0, 0, this );
shown on the applet.
25
26
// draw the image scaled to fit the width of the applet
27
// and the height of the applet minus 120 pixels
28
g.drawImage( logo1, 0, 120,
29
getWidth(), getHeight() - 120, this );
 2000 Prentice Hall, Inc. All rights reserved.
Outline
30
31
32
33
34 }
// draw the icon using its paintIcon method
logo2.paintIcon( this, g, 180, 0 );
}
3.2 paintIcon
Call to paintIcon, displays icon
Program Output
on this applet (a Component).
 2000 Prentice Hall, Inc. All rights reserved.
16.4 Loading and Playing Audio Clips
• Audio clips
– Require speakers and sound board
– Sound engine - plays audio clips
• Supports .au, .wav, .aif, .mid
• Java Media Framework supports additional formats
 2000 Prentice Hall, Inc. All rights reserved.
16.4 Loading and Playing Audio Clips
• Playing audio clips
– play method in Applet
– Plays clip once, marked for garbage collection when finished
play( location, soundFileName );
location - getDocumentBase (URL of HTML file)
play( soundURL );
soundURL - URL that contains location and filename of clip
 2000 Prentice Hall, Inc. All rights reserved.
16.4 Loading and Playing Audio Clips
• Playing audio clips
– Method play from AudioClip interface
• More flexible than Applet method play
• Audio stored in program, can be reused
– getAudioClip
• Returns reference to an AudioClip
• Same format as Applet method play
– getAudioClip( location, filename )
– getAudioClip( soundURL )
46
47
sound1 = getAudioClip(
getDocumentBase(), "welcome.wav" );
 2000 Prentice Hall, Inc. All rights reserved.
16.4 Loading and Playing Audio Clips
• Playing audio clips
– Once AudioClip loaded, use methods
• play - plays audio once
• loop - continuously loops audio in background
• stop - terminates clip that is currently playing
64
66
currentSound.play();
currentSound.loop();
68
currentSound.stop();
• Upcoming program
– Use a JComboBox to select between two sounds
 2000 Prentice Hall, Inc. All rights reserved.
Outline
1// Fig. 16.2: LoadAudioAndPlay.java
2// Load an audio clip and play it.
3import java.applet.*;
4import java.awt.*;
5import java.awt.event.*;
1. Declare objects
6import javax.swing.*;
7
1.1 GUI
8public class LoadAudioAndPlay extends JApplet {
9
private AudioClip sound1, sound2, currentSound;
10
private JButton playSound, loopSound, stopSound;
1.2 Event handler
11
private JComboBox chooseSound;
12
1.2.1 stop
13
// load the image when the applet begins executing
14
public void init()
15
{
16
Container c = getContentPane();
17
c.setLayout( new FlowLayout() );
18
19
String choices[] = { "Welcome", "Hi" };
20
chooseSound = new JComboBox( choices );
21
chooseSound.addItemListener(
22
new ItemListener() {
Once the selection changes, stop
23
public void itemStateChanged( ItemEvent
e )
currentSound
and set it equal to
24
{
either sound1 or sound2.
25
currentSound.stop();
26
27
currentSound =
28
chooseSound.getSelectedIndex() == 0 ?
29
sound1 : sound2;
 2000 Prentice Hall, Inc. All rights reserved.
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
}
}
Outline
);
c.add( chooseSound );
ButtonHandler handler = new ButtonHandler();
playSound = new JButton( "Play" );
playSound.addActionListener( handler );
c.add( playSound );
loopSound = new JButton( "Loop" );
loopSound.addActionListener( handler );
c.add( loopSound );
stopSound = new JButton( "Stop" );
stopSound.addActionListener( handler );
c.add( stopSound );
1.3 Register event
handlers
2. Initialize
AudioClips
3. Method stop
Notice how AudioClips are
initialized.
sound1 = getAudioClip(
getDocumentBase(), "welcome.wav" );
sound2 = getAudioClip(
getDocumentBase(), "hi.au" );
currentSound = sound1;
}
// stop the sound when the user switches Web pages
// (i.e., be polite to the user)
public void stop()
{
currentSound.stop();
}
 2000 Prentice Hall, Inc. All rights reserved.
Applet's stop method called when
user switches web pages. Ensures
clip stop playing (else could be
annoying to user).
60
61
62
63
64
65
private class ButtonHandler implements ActionListener {
public void actionPerformed( ActionEvent e )
{
if ( e.getSource() == playSound )
currentSound.play();
else if ( e.getSource() == loopSound )
66
67
currentSound.loop();
else if ( e.getSource() == stopSound )
68
69
70
71 }
currentSound.stop();
}
}
 2000 Prentice Hall, Inc. All rights reserved.
Outline
4. Event handler
Call methods play, loop, and
stop as appropriate.
4.1 play, loop, stop
16.5 The Java Media Player
• Java Media Player
– Comes with JMF
– Can play
• Audio: .au, .wav, .aiff, .mid
• Video: .avi, .gsm, .mpg (.mpeg), .mov, .rmf, .rtp,
.viv
Play/pause
Mute
Volume
Position
indicator
 2000 Prentice Hall, Inc. All rights reserved.
Information
16.5 The Java Media Player
• JFileChooser (javax.swing)
– Allows you to select a file
 2000 Prentice Hall, Inc. All rights reserved.
16.5 The Java Media Player
• JFileChooser (javax.swing)
35
JFileChooser fileChooser = new JFileChooser();
– Create JFileChooser
37
38
fileChooser.setFileSelectionMode(
JFileChooser.FILES_ONLY );
– Open only files (not directories)
39
int result = fileChooser.showOpenDialog( this );
– Returns an integer indicating user's action (selected file or
cancel)
42
43
if ( result == JFileChooser.CANCEL_OPTION )
file = null;
– If cancel, set file to null
 2000 Prentice Hall, Inc. All rights reserved.
16.5 The Java Media Player
44
45
else
file = fileChooser.getSelectedFile();
– Otherwise, call getSelectedFile and assign result to
file
• Class File discussed next chapter
10
57
private Player player;
player = Manager.createPlayer( file.toURL() );
– Returns object that implements Player interface
(javax.media)
• If file of correct format, returns object
• Method toURL converts file name and location into URL
format
 2000 Prentice Hall, Inc. All rights reserved.
16.5 The Java Media Player
58
player.addControllerListener( new EventHandler() );
59
player.start();
// start player
– Registers event handler
• Interface ControllerListener, must define
controllerUpdate
– Takes ControllerEvent objects
– Many subclasses, we use RealizeCompleteEvent
subclass
108
109
111
112
Component visualComponent =
player.getVisualComponent();
if ( visualComponent != null )
c.add( visualComponent, BorderLayout.CENTER );
– Adds visual aspect of media clips
• Audio clips return null
 2000 Prentice Hall, Inc. All rights reserved.
16.5 The Java Media Player
114
115
Component controlsComponent =
player.getControlPanelComponent();
117
118
if ( controlsComponent != null )
c.add( controlsComponent, BorderLayout.SOUTH );
– Display controls
120
c.doLayout();
– Update content pane
– Programmer-defined method removePreviousPlayer
73
player.close();
• Close current player
 2000 Prentice Hall, Inc. All rights reserved.
16.5 The Java Media Player
75
76
Component visual = player.getVisualComponent();
Component control = player.getControlPanelComponent();
80
if ( visual != null )
81
c.remove( visual );
83
if ( control != null )
84
c.remove( control );
– Get references to visual and control components
– Container method remove
• Remove Components from interface
 2000 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Fig. 16.3: MediaPlayerDemo.java
// Uses a Java Media Player to play media files.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.media.*;
Outline
1. Declarations
1.1 Constructor
public class MediaPlayerDemo extends JFrame {
private Player player;
private File file;
public MediaPlayerDemo()
{
super( "Demonstrating the Java Media Player" );
JButton openFile = new JButton( "Open file to play" );
openFile.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e )
{
openFile();
createPlayer();
}
}
);
getContentPane().add( openFile, BorderLayout.NORTH );
setSize( 300, 300 );
show();
}
 2000 Prentice Hall, Inc. All rights reserved.
32
33
34
35
36
37
38
39
40
41
private void openFile()
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(
JFileChooser.FILES_ONLY );
int result = fileChooser.showOpenDialog( this );
Create a JFileChooser,
use it to select a file.
2. Method openFile
2.1 JFileChooser
// user clicked Cancel button on dialog
42
if ( result == JFileChooser.CANCEL_OPTION )
43
file = null;
44
else
45
46
Outline
file = fileChooser.getSelectedFile();
2.2 file
Test for cancel option. If
not, assign file to file.
3. Method createPlayer
}
47
48
private void createPlayer()
49
{
50
51
if ( file == null )
return;
52
53
removePreviousPlayer();
54
55
try {
3.1 removePrevious
Player
Assign player
result of
3.2 createPlayer
createPlayer. Add event
handler (named inner class), call
3.3 Event
handler
start method
to being
playing
clip.
3.4 start
56
// create a new player and add listener
57
player = Manager.createPlayer( file.toURL() );
58
player.addControllerListener( new EventHandler() );
59
player.start();
60
// start player
}
 2000 Prentice Hall, Inc. All rights reserved.
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
catch ( Exception e ){
JOptionPane.showMessageDialog( this,
"Invalid file or location", "Error loading file",
JOptionPane.ERROR_MESSAGE );
}
}
private void removePreviousPlayer()
{
if ( player == null )
Close the
return;
Outline
4. removePrevious
Player
4.1 close
current player
4.2 remove
player.close();
Component visual = player.getVisualComponent();
Component control = player.getControlPanelComponent();
Container c = getContentPane();
if ( visual != null )
c.remove( visual );
Get references to
Components and
remove them from
content pane.
if ( control != null )
c.remove( control );
}
public static void main(String args[])
{
MediaPlayerDemo app = new MediaPlayerDemo();
 2000 Prentice Hall, Inc. All rights reserved.
5. main
91
app.addWindowListener(
92
Outline
new WindowAdapter() {
93
public void windowClosing( WindowEvent e )
94
{
95
System.exit(0);
96
}
97
}
98
99
6. Event handler
6.1
getVisualComponent
);
}
100
101
// inner class to handler events from media player
102
private class EventHandler implements ControllerListener {
103
public void controllerUpdate( ControllerEvent e ) {
104
105
Components and attach to
content pane.
if ( e instanceof RealizeCompleteEvent )Get
{
Container c = getContentPane();
106
107
// load Visual and Control components if they exist
108
Component visualComponent =
109
player.getVisualComponent();
110
111
112
if ( visualComponent != null )
c.add( visualComponent, BorderLayout.CENTER );
113
114
115
Component controlsComponent =
player.getControlPanelComponent();
116
117
6.2 getControlPanel
Component
if ( controlsComponent != null )
118
c.add( controlsComponent, BorderLayout.SOUTH );
 2000 Prentice Hall, Inc. All rights reserved.
Outline
119
120
c.doLayout();
121
}
122
123
}
}
6.3 doLayout
124 }
Program Output
 2000 Prentice Hall, Inc. All rights reserved.
Outline
Program Output
 2000 Prentice Hall, Inc. All rights reserved.
16.6 Animating a Series of Images
• Class Timer
– Generates ActionEvents at a fixed interval in
milliseconds
– Constructor:
Timer ( animationDelay, actionListener );
actionListener - ActionListener that will respond
to ActionEvents
– Methods
• start
• stop
• restart
• isRunning
 2000 Prentice Hall, Inc. All rights reserved.
16.6 Animating a Series of Images
• Method repaint
– Calls update, which calls paintComponent
• Subclasses of JComponent should use paintComponent
• Call superclass paintComponent first to display
components properly
30
super.paintComponent( g );
 2000 Prentice Hall, Inc. All rights reserved.
16.6 Animating a Series of Images
• View area
– Width and height specify entire window, not just client area
• Client area - where components can be displayed
– Dimension objects
• Constructor
– Dimension( width, height )
• Contains width and height instance variables
– Method setSize( width, height )
• Class JFrame
• Sets size of window
 2000 Prentice Hall, Inc. All rights reserved.
16.6 Animating a Series of Images
• getImageLoadStatus
– ImageIcon method
• Determines if image is completely loaded into memory
• Only complete images should be displayed (smooth animation)
– If loaded, returns MediaTracker.COMPLETE
32
33
if ( images[ currentImage ].getImageLoadStatus() ==
MediaTracker.COMPLETE ) {
– MediaTracker
• Can determine when images are loaded, or force program to
wait
• ImageIcon creates our MediaTracker for us
 2000 Prentice Hall, Inc. All rights reserved.
16.6 Animating a Series of Images
• Following example
– Use a series of images stored in an array
– Use Timer to generate ActionEvents
• Change image displayed
• Update content pane
 2000 Prentice Hall, Inc. All rights reserved.
1// Fig. 16.3: LogoAnimator.java
2// Animation a series of images
3import java.awt.*;
4import java.awt.event.*;
5import javax.swing.*;
1.1 Class
6
7public class LogoAnimator extends JPanel
LogoAnimator (
8
implements ActionListener {
implements
9
protected ImageIcon images[];
ActionListener)
10
protected int totalImages = 30,
11
currentImage = 0,
12
animationDelay = 50; // 50 millisecond delay
1.2 Declare objects
13
protected Timer animationTimer;
14
1.3 Constructor
15
public LogoAnimator()
16
{
Load array of ImageIcons to
17
setSize( getPreferredSize() );
use for the animation.1.4 Initialize
18
ImageIcon array
19
images = new ImageIcon[ totalImages ];
20
21
for ( int i = 0; i < images.length; ++i )
2. paintComponent
22
images[ i ] =
23
new ImageIcon( "images/deitel" + i + ".gif" );Call to superclass
24
2.1 super.paint
paintComponent
ensures
25
startAnimation();
Component
proper display.
26
}
27
28
public void paintComponent( Graphics g )
29
{
30
super.paintComponent( g );
31
 2000 Prentice Hall, Inc. All rights reserved.
Outline
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
if ( images[ currentImage ].getImageLoadStatus() ==
MediaTracker.COMPLETE ) {
images[ currentImage ].paintIcon( this, g, 0, 0 );
currentImage = ( currentImage + 1 ) % totalImages;
}
}
public void actionPerformed( ActionEvent e )
{
repaint();
}
Outline
2.2 getImage
LoadStatus
Check if the image
has
loaded, and if so, increment
currentImage.
2.3 Increment
currentImage
3. actionPerformed
Create new Timer, start. this
public void startAnimation()
{
applet listed as event handler.
if ( animationTimer == null ) {
3.1 startAnimation
currentImage = 0;
animationTimer = new Timer( animationDelay, this );
3.2 stopAnimation
animationTimer.start();
}
else // continue from last image displayed
if ( ! animationTimer.isRunning() )
animationTimer.restart();
If animationTimer is not
}
public void stopAnimation()
{
animationTimer.stop();
}
 2000 Prentice Hall, Inc. All rights reserved.
running (i.e. user switched web
pages and returned), restart it.
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
Outline
public Dimension getMinimumSize()
{
return getPreferredSize();
}
3.3 getMinimumSize
public Dimension getPreferredSize()
{
return new Dimension( 160, 80 );
}
public static void main( String args[] )
{
LogoAnimator anim = new LogoAnimator();
JFrame app = new JFrame( "Animator test" );
app.getContentPane().add( anim, fBorderLayout.CENTER );
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
 2000 Prentice Hall, Inc. All rights reserved.
3.4.
getPreferredSize
4. main
87
// The constants 10 and 30 are used below to size the
88
// window 10 pixels wider than the animation and
89
// 30 pixels taller than the animation.
90
app.setSize( anim.getPreferredSize().width + 10,
91
anim.getPreferredSize().height + 30 );
92
93
Outline
app.show();
}
94}
Program Output
 2000 Prentice Hall, Inc. All rights reserved.
16.7 Animation Issues
• Storing images
– Interlaced/non-interlaced formats
• Specifies order in which pixels are stored
• Non-interlaced - pixels stored in order they appear on screen
– Image appears in chunks from top to bottom as it is loaded
• Interlaced - pixels stored in rows, but out of order
– Image appears to fade in and become more clear
 2000 Prentice Hall, Inc. All rights reserved.
16.7 Animation Issues
• Animation flickers
– Due to update being called in response to repaint
– In AWT GUI components
• Draws filled rectangle in background color where image was
• Draw image, sleep, clear background (flicker), draw next
image...
– Swing's JPanel overrides update to avoid this
 2000 Prentice Hall, Inc. All rights reserved.
16.7 Animation Issues
• Double buffering
– Used to smooth animations
– Program renders one image on screen
• Builds next image in off-screen buffer
– When time to display next image, done smoothly
• Partial images user would have seen (while image loads) are
hidden
• All pixels for next image displayed at once
– Space/Time tradeoff
• Reduces flicker, but can slow animation speed and uses more
memory
– Used by Swing GUI components by default
 2000 Prentice Hall, Inc. All rights reserved.
16.8 Customizing Applets via the HTML
param Tag
• Applets
– Customize through parameters in HTML file that invokes
it
<html>
<applet code="LogoApplet.class" width=400
height=400>
<param name="totalimages" value="30">
<param name="imagename" value="deitel">
<param name="animationdelay" value="200">
</applet>
</html>
– Invokes applet LogoApplet
– param tags
• Each has a name and a value
• Use Applet method getParameter (returns a String)
parameter = getParameter( "animationdelay" );
 2000 Prentice Hall, Inc. All rights reserved.
16.8 Customizing Applets via the HTML
param Tag
• Following example
– Use the LogoAnimator class as before, but modified
slightly
• Include constructor to specify delay, name, number of images
– Create Applet LogoApplet
• Takes parameters
– totalimages
– imagename
– animationdelay
– Create LogoAnimator object using parameters (use new
constructor)
– Play animation
 2000 Prentice Hall, Inc. All rights reserved.
7
8
22
public class LogoAnimator extends JPanel
implements ActionListener {
public LogoAnimator( int num, int delay, String name )
Outline
127 import java.awt.*;
128 import javax.swing.*;
1. LogoAnimator
129
class as before, but
The LogoAnimator
130 public class LogoApplet extends JApplet{
class now has with
a newnew constructor
131
public void init()
constructor. --------------------132
{
133
String parameter;
134
1.1 getParameter
135
parameter = getParameter( "animationdelay" );
136
int animationDelay = ( parameter == null ? 50 :
137
Integer.parseInt( parameter ) );
1.2 LogoAnimator
138
139
String imageName = getParameter( "imagename" );
Get parameters from HTML file,
140
convert to integers.
141
parameter = getParameter( "totalimages" );
142
int totalImages = ( parameter == null ? 0 :
143
Integer.parseInt( parameter ) );
144
145
// Create an instance of LogoAnimator
146
LogoAnimator animator;
147
Create new
148
if ( imageName == null || totalImages == 0 )
LogoAnimator, use
149
animator = new LogoAnimator();
custom constructor if
150
else
applicable.
151
animator = new LogoAnimator( totalImages,
152
animationDelay, imageName );
 2000 Prentice Hall, Inc. All rights reserved.
Outline
153
154
155
156
157
158
159
160 }
setSize( animator.getPreferredSize().width,
animator.getPreferredSize().height );
getContentPane().add( animator, BorderLayout.CENTER );
2. setSize
animator.startAnimation();
}
2.3 startAnimation
Start the animation.
Program Output
 2000 Prentice Hall, Inc. All rights reserved.
16.9 Image Maps
• Image map
– Image that has hot areas
• User can click to accomplish a task
– Bubble help
• When mouse over particular point in screen, small message
displayed in status bar
• In the following example
– Load image containing several icons
– Use event handler mouseMoved to find x-coordinate
– Based on the x-coordinate, display a message
 2000 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Fig. 16.7: ImageMap.java
// Demonstrating an image map.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Outline
1. Declare objects
public class ImageMap extends JApplet {
private ImageIcon mapImage;
private int width, height;
2. init
2.1
public void init()
addMouseListener
{
addMouseListener(
new MouseAdapter() {
public void mouseExited( MouseEvent e )
{
showStatus( "Pointer outside applet" );
}
Pass the x coordinate to
}
translateLocation. This
);
returns a String, which is passed to
showStatus.
addMouseMotionListener(
new MouseMotionAdapter() {
public void mouseMoved( MouseEvent e )
{
showStatus( translateLocation( e.getX() ) );
}
}
);
 2000 Prentice Hall, Inc. All rights reserved.
31
32
33
34
35
36
37
38
39
40
41
42
43
mapImage = new ImageIcon( "icons2.gif" );
width = mapImage.getIconWidth();
height = mapImage.getIconHeight();
setSize( width, height );
}
public void paint( Graphics g )
{
mapImage.paintIcon( this, g, 0, 0 );
}
Outline
Determine width of
2.2 Initialize
mapimage.
ImageIcon
public String translateLocation( int x )
{
44
// determine width of each icon (there are 6)
45
int iconWidth = width / 6;
46
47
48
49
50
51
52
53
54
55
56
57
58
if ( x >= 0 && x <= iconWidth )
return "Common Programming Error";
else if ( x > iconWidth && x <= iconWidth * 2 )
return "Good Programming Practice";
else if ( x > iconWidth * 2 && x <= iconWidth * 3 )
return "Performance Tip";
else if ( x > iconWidth * 3 && x <= iconWidth * 4 )
return "Portability Tip";
else if ( x > iconWidth * 4 && x <= iconWidth * 5 )
return "Software Engineering Observation";
else if ( x > iconWidth * 5 && x <= iconWidth * 6 )
return "Testing and Debugging Tip";
 2000 Prentice Hall, Inc. All rights reserved.
3. paint
4.
translateLocation
Determine width of each icon
in image. Based on this,
display a message.
Outline
59
60
61
return "";
}
62 }
Program Output
 2000 Prentice Hall, Inc. All rights reserved.
16.10 Java Plug-In
• Web browsers
– Many different browser versions
– Most support Java 1.0 and 1.1, but few support Java 2
• Inconsistent support of 1.1
– To use Java 2 in an applet, use the Java Plug-in
• Bypasses browser's Java support
• Installs complete version of Java Runtime Environment on
user's computer
• Large file - ideal for corporate intranets and high-speed
networks
 2000 Prentice Hall, Inc. All rights reserved.
16.10 Java Plug-In
• Using the Plug in with applets
– The <applet>, <param> and </applet> tags must be
converted
• Must indicate that Plug-in should be used to execute applet
– Java Plug-in 1.2 HTML Converter
• Performs conversion for us
• http://java.sun.com/products/plugin/
– Execution
• In install directory type java HTMLConverter
• Select file to convert and type of conversion
 2000 Prentice Hall, Inc. All rights reserved.
16.11 Internet and World Wide Web
Resources
• Internet and web resources
– Java Media Framework
– Download and documentation:
http://java.sun.com/products/java-media/jmf/
– javax.media API descriptions:
http://java.sun.com/products/java-media/
jmf/forDevelopers/
 2000 Prentice Hall, Inc. All rights reserved.
16.11 Internet and World Wide Web
Resources
• Downloadable image, audio, and video galleries
– Test your multimedia programs
http://www.nasa.gov/gallery/index.html
http://sunsite.sut.ac.jp/multimed/
 2000 Prentice Hall, Inc. All rights reserved.