// CS 134 demo // Drag a shirt around window, given the choice of // a red shirt and a blue shirt. import objectdraw.*; import java.awt.*; public class Drag2Shirt extends WindowController { // starting location of t-shirt private static final int ITEM_LEFT = 75; private static final int ITEM_TOP = 50; private static final int SND_OFFSET = 150; // T-shirts on the screen private Tshirt redShirt, blueShirt; // The piece of laundry to be moved. private Tshirt selectedShirt; // Previously noted position of mouse cursor private Location lastPoint; // Whether user is actually dragging a shirt private boolean dragging; // display the shirts public void begin() { redShirt = new Tshirt( ITEM_LEFT, ITEM_TOP, canvas ); redShirt.setColor(Color.red); blueShirt = new Tshirt( ITEM_LEFT+SND_OFFSET, ITEM_TOP, canvas ); blueShirt.setColor(Color.blue); } // Whenever mouse is depressed, note its location // and determine which (if any) shirt mouse is on. public void onMousePress( Location point ) { lastPoint = point; if (blueShirt.contains(point)) { selectedShirt = blueShirt; dragging = true; } else if (redShirt.contains(point)) { selectedShirt = redShirt; dragging = true; } else { dragging = false; } } // If mouse is dragged, move the selected shirt with it // If didn't press mouse on a shirt, do nothing public void onMouseDrag( Location point ) { if ( dragging ) { selectedShirt.move( point.getX() - lastPoint.getX(), point.getY() - lastPoint.getY()); lastPoint = point; } } }