Computer Science 120
Introduction to Programming
Spring 2011, Siena College
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
*
* $Id: FallingBall.java 1536 2011-02-14 15:57:51Z 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
*
* $Id: FallingBalls.java 1536 2011-02-14 15:57:51Z terescoj $
*/
public class FallingBalls extends WindowController {
// the work happens here: create a FallingBall centered
// at the mouse position each time someone clicks
public void onMouseClick(Location point) {
new FallingBall(point, canvas);
}
}