Computer Science 252
Problem Solving with Java
Spring 2015, The College of Saint Rose
DragCars Demo
A working demo of DragCars will appear below. Click inside the applet to interact with it.
DragCars BlueJ Project
Click here to download a BlueJ project for DragCars.
DragCars Source Code
The Java source code for DragCars is below. Click on a file name to download it.
import objectdraw.*; import java.awt.*; /* * Example DragCars: example using a car to demonstrate a custom class * * Jim Teresco, The College of Saint Rose, CSC 252, Spring 2014 * * $Id: DragCars.java 2319 2014-02-07 01:24:52Z terescoj $ */ public class DragCars extends WindowController { // background colors private static final Color SKY_BLUE = new Color(175, 175, 255); private static final Color NIGHT_SKY = new Color(10, 10, 100); // the three cars, and the sky backgrounds private Car car1, car2, car3; private FilledRect lightSky, darkSky; // dragging support -- draggingCar is null if no dragging, a // reference to one of the cars if dragging private Location prevPoint; private Car draggingCar = null; public void begin() { // bright and dark portions lightSky = new FilledRect(0, 0, canvas.getWidth()/2, canvas.getHeight(), canvas); lightSky.setColor(SKY_BLUE); darkSky = new FilledRect(canvas.getWidth()/2, 0, canvas.getWidth()/2, canvas.getHeight(), canvas); darkSky.setColor(NIGHT_SKY); car1 = new Car(50, 50, Color.red, canvas); car2 = new Car(50, 250, Color.blue, canvas); car3 = new Car(200, 150, Color.green, canvas); } public void onMousePress(Location point) { if (car1.contains(point)) { draggingCar = car1; } else if (car2.contains(point)) { draggingCar = car2; } else if (car3.contains(point)) { draggingCar = car3; } prevPoint = point; } public void onMouseDrag(Location point) { if (draggingCar != null) { // standard dragging draggingCar.move(point.getX() - prevPoint.getX(), point.getY() - prevPoint.getY()); prevPoint = point; // check if we're supposed to turn the headlights on or off if (lightSky.contains(draggingCar.getCenter())) { draggingCar.turnOffHeadlights(); } else { draggingCar.turnOnHeadlights(); } } } public void onMouseRelease(Location point) { if (draggingCar != null) { // standard dragging draggingCar.move(point.getX() - prevPoint.getX(), point.getY() - prevPoint.getY()); prevPoint = point; // check if we're supposed to turn the headlights on or off if (lightSky.contains(draggingCar.getCenter())) { draggingCar.turnOffHeadlights(); } else { draggingCar.turnOnHeadlights(); } } draggingCar = null; } public void onMouseEnter(Location point) { car1.setColor(Color.red); car2.setColor(Color.blue); car3.setColor(Color.green); } public void onMouseExit(Location point) { if (car1.headlightsOn()) { car1.setColor(Color.gray); } if (car2.headlightsOn()) { car2.setColor(Color.gray); } if (car3.headlightsOn()) { car3.setColor(Color.gray); } } }