title: Difficulty understanding Java MouseEvent
body: <p>I'm doing these iTunes Stanford classes, and I've been learning beginning Java.  Things are going great, but they recently introduced events-and specifically MouseEvents.  I've been reading the chapters in the book, and pouring through the example code, and something is just not clicking right for me...it's always that asynchronous stuff that gives me trouble :-D</p>
  
  <p>Earlier, some people mentioned it was important that I mention that the "addMouseListener" is a class in the Graphics import.  As far as I can tell, that just adds a blanket mouse listener to the canvas.  </p>
  
  <p>I'm still real new to this, so I may not be describing things as well as I should.  </p>
  
  <p>This is a piece of code that I have been trying to simplify in order to better understand it.  Currently, it will build a red rectangle, and I can click on it and drag it along the x axis.  Great!!!</p>
  
  <pre><code>import java.awt.*;
  import java.awt.event.*;
  import acm.graphics.*;
  import acm.program.*;
  
  /** This class displays a mouse-draggable rectangle and oval */
  
  public class DragObject extends GraphicsProgram {
  
      /* Build a rectangle  */
      public void run() {
  
          GRect rect = new GRect(100, 100, 150, 100);
          rect.setFilled(true);
          rect.setColor(Color.RED);
          add(rect);
          addMouseListeners();
      }
  
  /** Called on mouse press to record the coordinates of the click */
      public void mousePressed(MouseEvent e) {
          lastX = e.getX();
          lastY = e.getY();
          gobj = getElementAt(lastX, lastY);
      }
  
  /** Called on mouse drag to reposition the object */
      public void mouseDragged(MouseEvent e) { 
  
              if((lastX) &gt; 100){
              gobj.move(e.getX() - lastX, 0);
  
              lastX = e.getX();
              lastY = e.getY();
          }
      }
  
  /** Called on mouse click to move this object to the front */
      public void mouseClicked(MouseEvent e) {
          if (gobj != null) gobj.sendToFront();
      }
  
  /* Instance variables */
  private GObject gobj;   /* The object being dragged */
  private double lastX;   /* The last mouse X position */
  private double lastY;   /* The last mouse Y position */
  }
  </code></pre>
  
  <p>If I drag the mouse off the canvas, I want the rectangle to stay within the canvas, and not move off it (the same behavior that a horizontal scroll bar would do if you moved beyond the scroll area with the mouse button still clicked).  How can I do that?  </p>
  
  <p>I've been trying something along these lines, but it's not working right:</p>
  
  <pre><code>    if  ( ( lastX &gt; (getWidth() - PADDLE_WIDTH) ) || ( lastX &lt; PADDLE_WIDTH ) ) {
          gobj.move(0, 0);
      } else {
          gobj.move(e.getX() - lastX, 0);
      }
  </code></pre>