home *** CD-ROM | disk | FTP | other *** search
/ Java 1.2 How-To / JavaHowTo.iso / javafile / ch07 / ImageMove.java < prev    next >
Encoding:
Java Source  |  1998-12-14  |  1.9 KB  |  95 lines

  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.applet.Applet;
  4.  
  5. /*
  6.  * the applet class
  7.  */
  8. public class ImageMove extends Applet implements΃
  9.  MouseListener, MouseMotionListener{
  10.  
  11. /*
  12.  * the image to be displayed
  13.  */
  14. Image img;
  15.  
  16. /*
  17.  * the width and height of the image
  18.  */
  19. int width, height;
  20.  
  21. /*
  22.  * xpos, ypos are the coordinates of the upper left of the image
  23.  */
  24. int xpos=10, ypos=10;
  25.  
  26. /*
  27.  * dx, dy are the deltas from the mouse point to xpos, ypos
  28.  */
  29. int dx, dy;
  30.  
  31. /*
  32.  * called when the applet is loaded
  33.  * load the image and use MediaTracker so that
  34.  * the width and height are available immediately
  35.  */
  36. public void init () {
  37.  
  38.     MediaTracker tracker = new MediaTracker (this); 
  39.  
  40.     img = getImage (getDocumentBase(), "T1.gif");
  41.     tracker.addImage (img, 0);
  42.     showStatus ("Getting image: T1.gif");
  43.     try {
  44.         tracker.waitForID (0);
  45.     } catch (InterruptedException e) { }
  46.     width = img.getWidth (this);
  47.     height = img.getHeight (this);
  48.     addMouseListener(this);
  49.     addMouseMotionListener(this); 
  50. }
  51.  
  52. /*
  53.  * paint the image in the new location
  54.  * @param g - destination graphics object
  55.  */
  56. public void paint (Graphics g) {
  57.  
  58.     g.setColor (Color.white);
  59.     g.drawImage (img, xpos, ypos, this);
  60. }
  61.  
  62.  
  63. /*
  64.  * adjust the new position and repaint the image
  65.  */
  66.  
  67. public void mouseClicked(MouseEvent e){}
  68. public void mouseEntered(MouseEvent e){}
  69. public void mouseExited(MouseEvent e){}
  70. public void mouseReleased(MouseEvent e){}
  71. public void mouseMoved(MouseEvent e){}
  72.  
  73. public void mousePressed(MouseEvent e)
  74. {
  75.     int x =e.getX();
  76.     int y =e.getY();
  77.  
  78.     dx = x - xpos;
  79.     dy = y - ypos;
  80. }
  81.  
  82. public void mouseDragged(MouseEvent e)
  83. {
  84.     int x =e.getX();
  85.     int y =e.getY();
  86.     if (dx < width && dx >= 0 && dy < height && dy >= 0)
  87.     {
  88.         xpos = x - dx;
  89.         ypos = y - dy;
  90.         repaint ();
  91.     }
  92. }
  93.  
  94. }
  95.