Mouse dragging: .contains() method and if statements - 09/13/2002



  1. Press down your mouse button and drag the purple box around on the Applet Canvas.

  2. Here is the Java code. It can be improved by using boolean variables. Boolean type is either True or False, like you are studying in Discrete Structures (propositions are either T or F).
    Preview/Study/Review the lecture notes that go with this code.
    // Mark Jacobson - September 12th, 2002 
    // To be handed out and discussed on Friday, Sept 13th in 810:061 class
    
    import objectdraw.*;
    import java.awt.*;
    
    public class WhatADrag extends WindowController {
    
       // Two private instance variables needed...  TWO instance variables.
    
       private FilledRect box; 
       private Location lastPoint;
    
       // Methods for the WhatADrag class follow.  There are THREE methods.
       public void begin() {
    
          box = new FilledRect(100, 100, 50, 25, canvas);
          box.setColor(Color.magenta);
    
          // Note that t is a LOCAL variable, local to the begin() method...
          Text t;
          t = new Text("Drag the box around with the mouse", 
                                                        50, 15, canvas);
          t.setBold();
          t.setColor(Color.blue);
    
          new Line(50, 15, 310, 15, canvas);
          new Line(50, 33, 310, 33, canvas); 
      }
    
       public void onMousePress(Location point) {
    
          lastPoint = point;
       }
    
       public void onMouseDrag(Location point) {
    
          if ( box.contains(lastPoint) )
          {
             box.move( point.getX() - lastPoint.getX(),
                       point.getY() - lastPoint.getY() );
             lastPoint = point;
          }     
       }
    }