growableballcollection.java

来自「书籍"Java_面向事件编程"的附带光盘代码」· Java 代码 · 共 75 行

JAVA
75
字号
import objectdraw.*;import java.awt.*;// A class that keeps track of a small collection of// basketballs drawn on the canvas.public class GrowableBallCollection implements BallCollectionInterface {        // the entire collection of balls.    private BBall[ ] balls;        // how many balls at the moment    private int ballCount = 0;        // limit on number of balls    private int maxBalls;        // used to pick random balls from the collection    private RandomIntGenerator picker;            // create a new, initially empty collection of basketballs    public GrowableBallCollection ( int size ) {                // create the array of slots for basketballs        balls = new BBall[size];        maxBalls = size;            }        // return true if there are currently no balls    public boolean isEmpty() {        return ballCount == 0;    }            // add an additional ball to the collection (if it will fit)    public void add( BBall newBall ) {        if ( ballCount < maxBalls ) {            balls[ballCount] = newBall;            ballCount++;                        picker = new RandomIntGenerator( 0, ballCount-1);                    } else {            System.out.println("WHOOPS!  Too many balls.");        }    }            // Return a random ball from the collection    public BBall pickRandomly() {        if ( ballCount > 0) {            return balls[ picker.nextValue() ];        } else {            return null;        }    }            // hide all the balls    public void hide() {        for ( int counter = 0; counter < ballCount; counter++) {            balls[counter].hide();        }    }        // show all the balls    public void show() {        for ( int counter = 0; counter < ballCount; counter++) {            balls[counter].show();        }    }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?