//********************************************************************
//  OffCenter.java       Author: Lewis and Loftus
//
//  Demonstrates the extension of an event adatpter class.
//********************************************************************

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;

public class OffCenter extends Applet
{
   private final int APPLET_WIDTH = 200;
   private final int APPLET_HEIGHT = 200;

   private DecimalFormat fmt;
   private Point current;
   private int centerX, centerY;
   private double length;

   //-----------------------------------------------------------------
   //  Sets up the applet, including creating a listener from the
   //  inner class and adding it to the applet.
   //-----------------------------------------------------------------
   public void init()
   {
      addMouseListener (new OffCenterListener());

      centerX = APPLET_WIDTH / 2;
      centerY = APPLET_HEIGHT / 2;

      fmt = new DecimalFormat ("0.##");

      setBackground (Color.yellow);
      setSize (APPLET_WIDTH, APPLET_HEIGHT);
   }

   //-----------------------------------------------------------------
   //  Draws a line from the mouse pointer to the center point of
   //  the applet and displays the distance.
   //-----------------------------------------------------------------
   public void paint (Graphics page)
   {
      page.setColor (Color.black);
      if (current != null)
      {
         page.drawLine (current.x, current.y, centerX, centerY);
         page.drawString ("Distance: " + fmt.format(length), 50, 15);
      }
   }

   class OffCenterListener extends MouseAdapter
   {
      //--------------------------------------------------------------
      //  Computes the distance from the mouse pointer to the center
      //  point of the applet.
      //--------------------------------------------------------------
      public void mouseClicked (MouseEvent event)
      {
         current = event.getPoint();
         length = Math.sqrt(Math.pow((current.x-centerX), 2) + 
                            Math.pow((current.y-centerY), 2));
         repaint();
      }
   }
}
