Sie sind auf Seite 1von 41

     

 

  


¦ 
 
 
      
 
  
 
       !
" 
 #
 # #$%

& '¦ ! ()*+$ ¦$, - 
   *./

| p  
  
p

 
 

r  
 !      
  "   #  $

| p  
  


 
 ' (

r   ! 


  %  &  
    
  ' ! ( á  ! )
    

| p  
  
*
    

r  +      & 
± java.awt.Image
‡ abstract ( &  )
r    ! ! 
  ,- +., /,
± javax.swg.ImageIc
r   

| p  
  
1 // Fig. 19.1: LoadImageAndScale.java ¦ 
2 // Load an image and display it in its original size and twice its
3 // original size. Load and display the same image as an ImageIcon.
4 import java.applet.Applet; ½aImageáca
5 import java.awt.*;
6 import javax.swing.*;
e.java
7
8 public class LoadImageAndScale extends JApplet { ½ 
9 private Image logo1;
10 private ImageIcon logo2;
¦&0 ! Image ½ 
11
12 // load image when applet is loaded &   
13 public void init() getImage ½ 
14 {
15 logo1 = getImage( getDocumentBase(), "logo.gif" ); ½ 
16 logo2 = new ImageIcon( "logo.gif" );
17 }
18
¦&0 ! ImageIc  '&
19 // display image   ImageIc  
rawImage  '
20 public void paint( Graphics g ) Image &0  
21 {
22 g.drawImage( logo1, 0, 0, this¦  rawImage
); // draw original image
23
 ' Image &0  
24 // draw image to fit the width and the height less 120 pixels
25 g.drawImage( logo1, 0, 120, getWidth(), getHeight() - 120, this );

| p  
 
 
" ¦ 
& // draw icon using its paintIcon method
0 logo2.paintIcon( this, g, 180, 0 );
 } atIc  ' ½aImageáca
1 ImageIc &0   e.java
} // end class LoadImageAndScale

½p1

 ¦

| p  
 
 
2


  

r    ! 


     '

| p  
  
1 // Fig. 19.2: LogoAnimator.java ¦ 
2 // Animation of a series of images.
3 import java.awt.*;
4 import java.awt.event.*; ½gámatr.ja
5 import javax.swing.*;
6
va
7 public class LogoAnimator extends JPanel implements ActionListener {
8 ½p
9 private final static String IMAGE_NAME = "deitel"; // base image name
10 protected ImageIcon images[]; // array of images
½p3 p1
11
12 private int totalImages = 30; // number of images
13 private int currentImage = 0; // current image index
14 private int animationDelay = 50; // millisecond delay
15 private int width; // image width
16 private int height; // image height
17
18 private Timer animationTimer; // Timer drives animation
19
20 // initialize LogoAnimator by loading images
21 public LogoAnimator()    ' 
22 { !ImageIc &0 
23 images = new ImageIcon[ totalImages ];
24
25 // load images
26 for ( int count = 0; count < images.length; ++count )
27 images[ count ] = new ImageIcon( getClass().getResource(
½ ImageIc
28 "images/" + IMAGE_NAME + count + ".gif" ) );
&0   '

| p  
 
 
29 ¦ 
30 // this example assumes all images have the same width and height
31 width = images[ 0 ].getIconWidth(); // get icon width
32 height = images[ 0 ].getIconHeight(); // get icon height ½gámatr.ja
33 }
34
va
35 // display current image
36 public void paintComponent( Graphics g ) ¦
½3%*4
37 { atmet ! 
38 super.paintComponent( g ); JPae  'ImageIc
½*1%4
39
40 images[ currentImage ].paintIcon( this, g, 0, 0 );
41
42 // move to next image only if timer is running
43 if ( animationTimer.isRunning() )
44 currentImage = ( currentImage + 1 ) % totalImages;
45 }
46
47 // respond to Timer's event
48 public void actionPerformed( ActionEvent actionEvent )
49 {

mer "
50 repaint(); // repaint animator actPerfrme '
51 } amat eay (50)
52   
53 // start or restart animation
54 public void startAnimation()
55 {

| p  
 
 
56 if ( animationTimer == null ) { ¦ 
57 currentImage = 0;
58 animationTimer = new Timer( animationDelay, this );
59 animationTimer.start(); ½gámatr.ja
60 }
61 else // continue from last image displayed
va
62 if ( ! animationTimer.isRunning() )
63 animationTimer.restart(); ½3
64 }
65
66 // stop animation timer
67 public void stopAnimation()
68 { st  
69 animationTimer.stop();  
mer  
70 }
71
 
72 // return minimum size of animation
73 public Dimension getMinimumSize()
74 {
75 return getPreferredSize();
76 }
77
78 // return preferred size of animation
79 public Dimension getPreferredSize()
80 {
81 return new Dimension( width, height );
82 }
83

| p  
 
 
84 // execute animation in a JFrame ¦ 
85 public static void main( String args[] )
86 {
87 LogoAnimator animation = new LogoAnimator(); // create LogoAnimator ½gámatr.ja
88
89 JFrame window = new JFrame( "Animator test" ); // set up window
va
90 window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
91
92 Container container = window.getContentPane();
93 container.add( animation );
94
95 window.pack(); // make window just large enough for its GUI
96 window.setVisible( true ); // display window
97 animation.startAnimation(); // begin animation
98
99 } // end method main
100
101 } // end class LogoAnimator

| p  
 
 
p

 

r   
  i 
r    5   

| p  
  
1 // Fig. 19.3: ImageMap.java ¦ 
2 // Demonstrating an image map.
3 import java.awt.*;
4 import java.awt.event.*; ImageMa.java
5 import javax.swing.*;
6
7 public class ImageMap extends JApplet { ½1%
8 private ImageIcon mapImage;
9
10 private static final String captions[] = { "Common Programming Error",
11 "Good Programming Practice", "Graphical User Interface Tip",
12 "Performance Tip", "Portability Tip",
13 "Software Engineering Observation", "Error-Prevention Tip" };
14
15 // set up mouse listeners
16 public void init()
17 { M se½steer !5
18 addMouseListener( 6   
19
20 new MouseAdapter() { // anonymous inner class
21
22 // indicate when mouse pointer exits applet area
23 public void mouseExited( MouseEvent event )
24 {
25 showStatus( "Pointer outside applet" );
26 }
27
28 } // end anonymous inner class
29
30 ); // end call to addMouseListener

| p  
 
 
 ¦ 
M seMt½steer
 addMouseMotionListener(
 !  
 new MouseMotionAdapter() { // anonymous inner class ImageMa.java

" // determine icon over which mouse appears ½p%*4
& public void mouseMoved( MouseEvent event )
0 {
½3%23
 showStatus( translateLocation(
1 event.getX(), event.getY() ) );
 }

 } // end anonymous inner class

 ); // end call to addMouseMotionListener
"
& mapImage = new ImageIcon( "icons.png" ); // get image
0
 } // end method init
1
 // display mapImage
 public void paint( Graphics g )
 {
 super.paint( g );
 mapImage.paintIcon( this, g, 0, 0 );
" }
&

| p  
 
 
58 // return tip caption based on mouse coordinates   
¦ 
59 public String translateLocation( int x, int y )  5 
60 {
5 
61 // if coordinates outside image, return immediately ImageMa.java
62 if ( x >= mapImage.getIconWidth() || y >= mapImage.getIconHeight() )
63 return "";
64 ½3p
65 // determine icon number (0 - 6)
66 int iconWidth = mapImage.getIconWidth() / 7;
67 int iconNumber = x / iconWidth;
68
69 return captions[ iconNumber ]; // return appropriate icon caption
70 }
71
72 } // end class ImageMap

| p  
 
 
¦ 

ImageMa.java

 ¦

| p  
 
 
¦ 

ImageMa.java

 ¦

| p  
 
 
1

      !

r  '  


  '! áet
  '! á 
 +  7
r   ! ! 
 (.a )
 858 (.wav)
  --(.af .aff)
   ! ()(.m)

| p  
  
// Fig. 19.4: LoadAudioAndPlay.java ¦ 
// Load an audio clip and play it.

import java.applet.*; ½aá áPa
import java.awt.*; y.java
"import java.awt.event.*;
&import javax.swing.*;
½
0
public class LoadAudioAndPlay extends JApplet {  
1 private AudioClip sound1, sound2, currentSound; á  &0 
 private JButton playSound, loopSound, stopSound;
 private JComboBox chooseSound;

 // load the image when the applet begins executing
 public void init()
" {
& Container container = getContentPane();
0 container.setLayout( new FlowLayout() );

1 String choices[] = { "Welcome", "Hi" };
 chooseSound = new JComboBox( choices );

 chooseSound.addItemListener(

 new ItemListener() {
"

| p  
 
 
27 // stop sound and change to sound to user's selection ¦ 
28 public void itemStateChanged( ItemEvent e )
29 {
30 currentSound.stop(); ½aá áPa
31
32 currentSound =
y.java
33 chooseSound.getSelectedIndex() == 0 ? sound1 : sound2;
34 } ½3p%3
35
36 } // end anonymous inner class
37
38 ); // end addItemListener method call
39
40 container.add( chooseSound );
41
42 // set up button event handler and buttons
43 ButtonHandler handler = new ButtonHandler();
44
45 playSound = new JButton( "Play" );
46 playSound.addActionListener( handler );
47 container.add( playSound );
48
49 loopSound = new JButton( "Loop" );
50 loopSound.addActionListener( handler );
51 container.add( loopSound );

| p  
 
 
 ¦ 
 stopSound = new JButton( "Stop" );
 stopSound.addActionListener( handler ); getá   
 container.add( stopSound ); ! á  &0 áPa
½aá
"
& // load sounds and set currentSound
y.java
0 sound1 = getAudioClip( getDocumentBase(), "welcome.wav" );
 sound2 = getAudioClip( getDocumentBase(), "hi.au" ); ½31%4
"1 currentSound = sound1;
"
" } // end method init
"
" // stop the sound when the user switches Web pages
" public void stop()
"" {
"& currentSound.stop();
"0 }
"
&1 // private inner class to handle button events
& private class ButtonHandler implements ActionListener {
&

| p  
 
 
& // process play, loop and stop button events ¦ 
& public void actionPerformed( ActionEvent actionEvent )
& {
&" if ( actionEvent.getSource() == playSound ) ½aá áPa
&& currentSound.play(); ay
y.java 
&0  '  
& else if ( actionEvent.getSource() == loopSound )
½22
01 currentSound.loop(); s  '
0    '
0 else if ( actionEvent.getSource() == stopSound ) st 
½1
0 currentSound.stop();
 '  
½1
0 }
0
0" } // end class ButtonHandler
0&
00} // end class LoadAudioAndPlay

| p  
 
 
p
&'¦ ! ()*+$ 
¦$, -    *./
‡ ImagePae
 !&0     '
r  *r Eevatr aft
‡ MvgPae
 !&0  #$
r  Eevatr
‡ ámatePae
 !&0  #  $
r  Pers  r B tt Be ½g t

| p  
  
p*
&'¦ ! ()*+$ 
¦$, -    *./
' (

javax.swg.JPae
  O

   
O O
O O

O O

    

 

* 

    
   

| p  
  
// ImagePanel.java ¦ 
// JPanel subclass for positioning and displaying ImageIcon
package com.deitel.jhtp5.elevator.view;
 ImagePae.java
// Java core packages
"import java.awt.*; ½
ImagePae 6
&import java.awt.geom.*;
JPae ImagePae
0import java.util.*;
& '  ½3

1// Java extension packages
import javax.swing.*; ½

public class ImagePanel extends JPanel { . ImagePae ½p4
   9!
 // identifier
" private int ID;
&
0 // on-screen position Pt2 .  be
 private Point2D.Double position; !! !6%'
1   
 // imageIcon to paint on screen
 private ImageIcon imageIcon;

 // stores all ImagePanel children
 private Set panelChildren; !ImagePae  
"

| p  
 
 
& // constructor initializes position and image ¦ 
0 public ImagePanel( int identifier, String imageName )
 {
1 super( null ); // specify null layout ImagePae.java
 setOpaque( false ); // make transparent
 ½*%*p
 // set unique identifier
 ID = identifier;

" // set location
& position = new Point2D.Double( 0, 0 );
0 setLocation( 0, 0 );
mageName 
   ImageIc  
1 // create ImageIcon with given imageName 5 & ' 
 imageIcon = new ImageIcon(
 getClass().getResource( imageName ) );

 Image image = imageIcon.getImage();
 setSize(
" image.getWidth( this ), image.getHeight( this ) );
&
0 // create Set to store Panel children
 panelChildren = new HashSet();
1
 } // end ImagePanel constructor


| p  
 
 
 // paint Panel to screen  'ImagePae¦( 

 public void paintComponent( Graphics g ) ImageIc) 
 {
" super.paintComponent( g ); ImagePae.java
&
0 // if image is ready, paint it to screen ½4*%3
 imageIcon.paintIcon( this, g, 0, 0 );
"1 }
½3%32
"
" // add ImagePanel child to ImagePanel
" public void add( ImagePanel panel ) ½2 
¦a %2*
" { ImagePae  
" panelChildren.add( panel );
"" super.add( panel );
"& }
"0
" // add ImagePanel child to ImagePanel at given index
¦  a 
&1 public void add( ImagePanel panel, int index )
& {
ImagePae  
& panelChildren.add( panel );
& super.add( panel, index );
& }
&

| p  
 
 
&" // remove ImagePanel child from ImagePanel ¦ 
¦remve 
&& public void remove( ImagePanel panel )
&0 { ImagePae  
& panelChildren.remove( panel ); ImagePae.java
01 super.remove( panel );
0 } ½22%1
0
0 // sets current ImageIcon to be displayed
0 public void setIcon( ImageIcon icon )
0 {
0" imageIcon = icon;
0& }
00
0 // set on-screen position
1 public void setPosition( double x, double y )
 {
 position.setLocation( x, y );
 setLocation( ( int ) x, ( int ) y );
 }

" // return ImagePanel identifier
& public int getID()
0 {
 return ID;
11 }
1

| p  
 
 
1 // get position of ImagePanel ¦ 
1 public Point2D.Double getPosition()
1 {
1 return position; ImagePae.java
1" }
1& ½ %1
10 // get imageIcon
1 public ImageIcon getImageIcon()
1 {
 return imageIcon;  
 }

 // get Set of ImagePanel children
 public Set getChildren()
" {
& return panelChildren;
0 }
}

| p  
 
 
// MovingPanel.java ¦ 
// JPanel subclass with on-screen moving capabilities
package com.deitel.jhtp5.elevator.view;
 MvgPae.jav
// Java core packages a
"import java.awt.*;
&import java.awt.geom.*;
½
0import java.util.*;
 MvgPae 
1// Java extension packages
½p %p
&0 
import javax.swing.*;

public class MovingPanel extends ImagePanel {

 // should MovingPanel change position?
" private boolean moving;
&
0 // number of pixels MovingPanel moves in both x and y values
 // per animationDelay milliseconds  be 
1 private double xVelocity;
  '5% 
 private double yVelocity;

 // constructor initializes position, velocity and image
 public MovingPanel( int identifier, String imageName )
 {
" super( identifier, imageName );
&

| p  
 
 
28 // set MovingPanel velocity
29 xVelocity = 0; ¦ 
30 yVelocity = 0;
31
32 } // end MovingPanel constructor MvgPae.jav
33 a
34 // update MovingPanel position and animation frame
35 public void animate()
36 { ½1%4p
37 // update position according to MovingPanel velocity
!MvgPae  
38 if ( isMoving() ) {  MvgPae
39 double oldXPosition = getPosition().getX();   5  !
40 double oldYPosition = getPosition().getY(); MvgPae7  
41
42 setPosition( oldXPosition + xVelocity,
43 oldYPosition + yVelocity );
44 }
45
46 // update all children of MovingPanel
47 Iterator iterator = getChildren().iterator();
48
49 while ( iterator.hasNext() ) {
50 MovingPanel panel = ( MovingPanel ) iterator.next();
51 panel.animate();
52 }
53 } // end method animate
54
55 // is MovingPanel moving on screen?
56 public boolean isMoving()
57 {
58 return moving;
59 } | p  
 
60  
" // set MovingPanel to move on screen ¦ 
" public void setMoving( boolean move )
" {
" moving = move; MvgPae.jav
" } a
""
"& // set MovingPanel x and y velocity
½31%1*
"0 public void setVelocity( double x, double y )
" {
&1 xVelocity = x;
& yVelocity = y;
& }
&
& // return MovingPanel x velocity
& public double getXVelocity()
&" {
&& return xVelocity;
&0 }
&
01 // return MovingPanel y velocity
0 public double getYVelocity()
0 {
0 return yVelocity;
0 }
0}

| p  
 
 
// AnimatedPanel.java ¦ 
// MovingPanel subclass with animation capabilities
package com.deitel.jhtp5.elevator.view;
 ámatePae.j
// Java core packages ava
"import java.awt.*;
ámatePae
&import java.util.*;
&0  ½p
0
// Java extension packages     
1import javax.swing.*; ! !   ½%p

public class AnimatedPanel extends MovingPanel { ½p

 // should ImageIcon cycle frames ½p3%p2
 private boolean animating;
"
& // frame cycle rate (i.e., rate advancing to next frame) ImageIc  ' 
0 private int animationRate;
:  &      
 private int animationRateCounter;     9 
1 private boolean cycleForward = true;

 // individual ImageIcons used for animation frames
 private ImageIcon imageIcons[];

 // storage for all frame sequences
" private java.util.List frameSequences; :  & 5 
& private int currentAnimation; ! !   '

| p  
 
 
28 ¦ 
29 // should loop (continue) animation at end of cycle?
30 private boolean loop;
31 ámatePae.j
32 // should animation display last frame at end of animation?
33 private boolean displayLastFrame;
ava
34
35 // helps determine next displayed frame ½**%*
36 private int currentFrameCounter;
37
½43%2
38 // constructor takes array of filenames and screen position
39 public AnimatedPanel( int identifier, String imageName[] )
40 {
41 super( identifier, imageName[ 0 ] );
42
43 // creates ImageIcon objects from imageName string array
44 imageIcons = new ImageIcon[ imageName.length ];
45
ámatePae  
46 for ( int i = 0; i < imageIcons.length; i++ ) {
47 imageIcons[ i ] = new ImageIcon(
 ImageIc  '!
48 getClass().getResource( imageName[ i ] ) );   '  5 
49 }   ! ! 
50
51 frameSequences = new ArrayList();
52
53 } // end AnimatedPanel constructor
54
¦amate !
55 // update icon position and animation frame
56 public void animate() MvgPae  
57 { ámatePae 
58 super.animate();  ! !  
| p  
 
 
 ¦ 
"1 // play next animation frame if counter > animation rate
" if ( frameSequences != null && isAnimating() ) {
 '6! !
" ámatePae.j
 
" if ( animationRateCounter > animationRate ) { ava
" animationRateCounter = 0;
" determineNextFrame();
½3%3
"" }
"& else
"0 animationRateCounter++;
½2%
" }
&1 } // end method animate ½1*%
&
& // determine next animation frame
 ' 
& private void determineNextFrame()
& {
6! !   '
& int frameSequence[] =
&" ( int[] ) frameSequences.get( currentAnimation );
&&
&0 // if no more animation frames, determine final frame,
& // unless loop is specified
01 if ( currentFrameCounter >= frameSequence.length ) {
0 currentFrameCounter = 0; !   ! 
0 fase     ! 
0 // if loop is false, terminate animation
0 if ( !isLoop() ) {
0
0" setAnimating( false );
0& | p  
 
 
88 if ( isDisplayLastFrame() ) ½ ! 9  '!
¦ 
89 say½ast*rame tr e 
90 // display last frame in sequence
!! 9 
91 currentFrameCounter = frameSequence.length - 1; ámatePae.j
92 }
 '!say½ast*rame
93 }
ava
fase
94
95 // set current animation frame ½11%
96 setCurrentFrame( frameSequence[ currentFrameCounter ] );
97 currentFrameCounter++;
½3%2
98  set rret-
99 } // end method determineNextFrame
*rame ImageIc
100
101 (   ')
// add frame sequence (animation) to frameSequences ArrayList
102 public void addFrameSequence( int frameSequence[] )ImageIc !
103 {  ! 9 
104 frameSequences.add( frameSequence );
105 }
106
107 // ask if AnimatedPanel is animating (cycling frames)
108 public boolean isAnimating()
109 {
110 return animating;
111 }
112
113 // set AnimatedPanel to animate
114 public void setAnimating( boolean animate )
115 {
116 animating = animate;
117 }

| p  
 
 
118 ¦ 
119 // set current ImageIcon
120 public void setCurrentFrame( int frame )
121 { ámatePae.j
122 setIcon( imageIcons[ frame ] );
123 }
ava
124
125 // set animation rate
126 public void setAnimationRate( int rate )
127 {
128 animationRate = rate;
129 }
130
131 // get animation rate
132 public int getAnimationRate()
133 {
134 return animationRate;
135 }
136
137 // set whether animation should loop
138 public void setLoop( boolean loopAnimation )
139 {
140 loop = loopAnimation;
141 }
142
143 // get whether animation should loop
144 public boolean isLoop()
145 {
146 return loop;
147 }
148
| p  
 
 
 // get whether to display last frame at animation end ¦ 
1 private boolean isDisplayLastFrame()
 {
 return displayLastFrame; ámatePae.j
 } ava

 // set whether to display last frame at animation end
½3p%32
" public void setDisplayLastFrame( boolean displayFrame )
& {
0 displayLastFrame = displayFrame;
 }
"1
" // start playing animation sequence of given index
" public void playAnimation( int frameSequence ) l  
" {
" currentAnimation = frameSequence;
" currentFrameCounter = 0;
"" setAnimating( true );
"& }
"0}

| p  
 
 
&'¦ ! ()*+$  

¦$, -    *./


'! (


  
  


 ? ? O   

O ? O  O ?   
  

? O     O ?  

    ?   

*   
  imageIcons  List frameSequences

| p  
  
// SoundEffects.java ¦ 
// Returns AudioClip objects
package com.deitel.jhtp5.elevator.view;
  Effects.ja
// Java core packages  !!  va
"import java.applet.*; (á )!5
&
½1
0public class SoundEffects {

1 // location of sound files
½%p
 private String prefix = "";

 s *e   
 public SoundEffects() {} statc ewá 
 (! java.aet.áet)
 // get AudioClip associated with soundFile á  &0 
" public AudioClip getAudioClip( String soundFile )
& {
0 try {
 return Applet.newAudioClip( getClass().getResource(
1 prefix + soundFile ) );
 }

 // return null if soundFile does not exist
 catch ( NullPointerException nullPointerException ) {
 return null;
" }
& }

| p  
 
 
0 ¦ 
 // set prefix for location of soundFile
1 public void setPathPrefix( String string )
 {  Effects.ja
 prefix = string; va
 }
}

| p