Computer Science 252
Problem Solving with Java
Fall 2015, The College of Saint Rose
UglyDragABall Demo
A working demo of UglyDragABall will appear below. Click inside the applet to interact with it.
UglyDragABall BlueJ Project
Click here to download a BlueJ project for UglyDragABall.
UglyDragABall Source Code
The Java source code for UglyDragABall is below. Click on a file name to download it.
import objectdraw.*;
import java.awt.*;
/*
* Example UglyDragABall
* Simple example to demonstrate dragging of a graphical object
* but not in a very nice fashion
*
* Jim Teresco, Siena College, CSIS 120, Spring 2011
* The College of Saint Rose, Fall 2013
*
* $Id: UglyDragABall.java 2528 2015-01-22 03:05:27Z terescoj $
*/
public class UglyDragABall 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;
// 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;
}
else {
ballGrabbed = false;
}
}
// complete the drag to the release point, stop the dragging
public void onMouseRelease(Location point) {
if (ballGrabbed) {
ball.moveTo(point);
ballGrabbed = false;
}
}
// if we are dragging, move the ball to follow the mouse,
// update lastMouse location
public void onMouseDrag(Location point) {
if (ballGrabbed) {
// the moveTo method does an absolute move to the given
// Location regardless of the object's previous position
ball.moveTo(point);
}
}
}