Computer Science 252
Problem Solving with Java
Spring 2015, The College of Saint Rose
FallingBalls Demo
A working demo of FallingBalls will appear below. Click inside the applet to interact with it.
FallingBalls BlueJ Project
Click here to download a BlueJ project for FallingBalls.
FallingBalls Source Code
The Java source code for FallingBalls is below. Click on a file name to download it.
import objectdraw.*; import java.awt.*; /* * Example FallingBalls * * A simple active object that controls a ball that falls down the * canvas * * Jim Teresco, Siena College, CSIS 120, Spring 2011 * The College of Saint Rose, Fall 2013 * * $Id: FallingBall.java 2218 2013-10-18 14:06:39Z terescoj $ */ public class FallingBall extends ActiveObject { // size and speed of falling balls private static final int BALLSIZE = 30; private static final double Y_SPEED = 8; private static final int DELAY_TIME = 33; // the ball controlled by this instance private FilledOval ball; // how far to fall before stopping and disappearing? private double yMax; // Draw a ball and start it falling. public FallingBall(Location start, DrawingCanvas aCanvas) { // draw the ball at its initial position ball = new FilledOval(start.getX() - BALLSIZE/2, start.getY() - BALLSIZE/2, BALLSIZE, BALLSIZE, aCanvas); // ask the canvas how big it is so we know when to stop yMax = aCanvas.getHeight(); // activate! start(); } // move the ball repeatedly until it falls off screen public void run() { while (ball.getY() <= yMax) { ball.move(0, Y_SPEED); pause(DELAY_TIME); } ball.removeFromCanvas(); } }
import objectdraw.*; import java.awt.*; /* * Example FallingBalls: create an active object representing a ball * on each mouse click * * Jim Teresco, Siena College, CSIS 120, Spring 2011 * The College of Saint Rose, Fall 2013, Spring 2014 * * $Id: FallingBalls.java 2321 2014-02-10 18:50:27Z terescoj $ */ public class FallingBalls extends WindowController { // the work happens here: create a FallingBall centered // at the mouse position each time someone presses public void onMousePress(Location point) { new FallingBall(point, canvas); } }