Computer Science 120
Introduction to Programming
Fall 2011, Siena College
DragABall Demo
A working demo of DragABall will appear below. Click inside the applet to interact with it.
DragABall BlueJ Project
Click here to download a BlueJ project for DragABall.
DragABall Source Code
The Java source code for DragABall is below. Click on a file name to download it.
import objectdraw.*; import java.awt.*; /* * Example DragABall * Simple example to demonstrate dragging of a graphical object * * Jim Teresco, Siena College, CSIS 120, Fall 2011 * * $Id: DragABall.java 1507 2011-01-27 02:20:59Z terescoj $ */ public class DragABall extends WindowController { // named constants for the size and initial location of the ball private static final int BALL_DIAMETER = 50; private static final Location BALL_START = new Location(100, 100); // a ball private FilledOval ball; // the last previous known location of the mouse private Location lastMouse; // Is the ball currently being dragged around the screen? private boolean ballGrabbed; // place the ball on the canvas to start public void begin() { ball = new FilledOval(BALL_START, BALL_DIAMETER, BALL_DIAMETER, canvas); } // check if the mouse is pressed on the ball -- if so, set up for // dragging public void onMousePress(Location point) { if (ball.contains(point)) { // note that we've grabbed the ball and remember this point ballGrabbed = true; lastMouse = point; } } // complete the drag to the release point, stop the dragging public void onMouseRelease(Location point) { if (ballGrabbed) { ball.move(point.getX() - lastMouse.getX(), point.getY() - lastMouse.getY()); ballGrabbed = false; } } // if we are dragging, move the ball to follow the mouse, // update lastMouse location public void onMouseDrag(Location point) { if (ballGrabbed) { ball.move(point.getX() - lastMouse.getX(), point.getY() - lastMouse.getY()); lastMouse = point; } } }