// file:    miniMouse.java
// author:  Robert M. Keller
// purpose: minimal mouse-tracking applet

// As mouse events occur, the event and its coordinates appear on the screen.

// This applet also prescribes a model for the use of double-buffering 
// to avoid flicker: drawing occurs in an image buffer, which is then 
// painted onto the screen as needed.  This also simplifies drawing, 
// since each event creates a blank slate and then draws onto it.

import java.applet.*;           // applet class
import java.awt.*;              // Abstract Window Toolkit


public class miniMouse extends Applet
  {
  Image image;                  // Image to be drawn on screen by paint method
  Graphics graphics;            // Graphics part of image, acts as buffer


  // Initialize the applet.

  public void init()
    {
    makeImageBuffer();
    }


   // mouseDown is called when the mouse button is depressed.

  public boolean mouseDown(Event e, int x, int y)
    {
    return show("mouseDown", x, y);
    }


   // mouseDrag is called when the mouse is dragged.

  public boolean mouseDrag(Event e, int x, int y)
    {
    return show("mouseDrag", x, y);
    }


   // mouseUp is called when the mouse button is released.

  public boolean mouseUp(Event v, int x, int y)
    {
    return show("mouseUp", x, y);
    }


   // mouseMove is called when the mouse moves without being dragged

  public boolean mouseMove(Event v, int x, int y)
    {
    return show("mouseMove", x, y);
    }


   // mouseEnter is called when the mouse enters the applet

  public boolean mouseEnter(Event v, int x, int y)
    {
    return show("mouseEnter", x, y);
    }


   // mouseExit is called when the mouse leaves the applet

  public boolean mouseExit(Event v, int x, int y)
    {
    return show("mouseExit", x, y);
    }


  // show paints the mouse coordinates into the graphics buffer

  boolean show(String message, int x, int y)
    {
    clear();
    graphics.setColor(Color.black);
    graphics.drawString(message + " at (" + x + ", " + y + ")", 50, 100);
    repaint();
    return true;
    }


  // update is implicitly called when repaint() is called
  // g will be bound to the Graphics object in the Applet,
  // not the one in the image.  paint will draw the image into g.

  public void update(Graphics g)
    {
    paint(g);
    }


  // paint(Graphics) is called by update(g) and whenever 
  // the screen needs painting (such as when it is newly exposed)

  public void paint(Graphics g)
    {
    g.drawImage(image, 0, 0, null);
    }


  // clear clears the image

  void clear()
    {
    graphics.clearRect(0, 0, size().width, size().height);
    graphics.drawRect(0, 0, size().width-1, size().height-1);
    }

  // Make image buffer based on size of the applet.

  void makeImageBuffer()
    {
    image = createImage(size().width, size().height);	
    graphics = image.getGraphics();
    }
  }

