Source of MouseMotionApplet.java


  1: //MouseMotionApplet.java
  2: //Applet to demonstrate mouse motion over an image

  4: import java.awt.*;
  5: import java.awt.event.*;
  6: import java.applet.*;

  8: public class MouseMotionApplet
  9:     extends Applet
 10:     implements MouseMotionListener
 11: {
 12:     //Declare single image variable
 13:     Image musicians;

 15:     public void init()
 16:     {
 17:         //Get image from the file and assign to musicians variable
 18:         musicians = getImage(getDocumentBase(),
 19:                              "images/musicians.jpg");
 20:         //Add motion listener to detect movement of the mouse
 21:         addMouseMotionListener(this);
 22:     }

 24:     //Paint single image of musicians
 25:     public void paint(Graphics g)
 26:     {
 27:         g.drawImage(musicians, 100, 100, 200, 150, this);
 28:     }

 30: 
 31:     //Implement methods in the MouseMotionListener interface
 32:     //------------------------------------------------------
 33:     //Move mouse over picture to display names of musicians
 34:     public void mouseMoved(MouseEvent event)
 35:     {
 36:         int x = event.getX();
 37:         int y = event.getY();
 38:         Graphics g = getGraphics();

 40:         //Erase previous name from window and get
 41:         //ready to display another name ...
 42:         g.setColor(getBackground());
 43:         g.fillRect(100, 255, 200, 45);
 44:         g.setColor(Color.black);

 46:         //Display the name of the musician if the
 47:         //mouse is positioned more or less on his shirt
 48:         if (x>=110 && x<=160 && y>=155 && y<=190)
 49:         {
 50:             g.drawString("That's", 120, 275);
 51:             g.drawString("Tom",    120, 290);
 52:         }
 53:         else if (x>190 && x<=235 && y>=170 && y<=205)
 54:         {
 55:             g.drawString("That's", 200, 275);
 56:             g.drawString("Dick",   200, 290);
 57:         }
 58:         else if (x>240 && x<=300 && y>=180 && y<=220)
 59:         {
 60:             g.drawString("That's", 250, 275);
 61:             g.drawString("Harry",  250, 290);
 62:         }
 63:         else if (x < 110 || x > 235 || y < 155 || y > 220)
 64:         {
 65:             g.setColor(getBackground());
 66:             g.fillRect(100, 255, 200, 45);
 67:         }
 68:     }
 69:     //This method left empty ...
 70:     public void mouseDragged(MouseEvent event){}
 71: }