AnimatedBalls.java
package com.bozoid.cis370.hw07;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*; // for Ellipse2D
import java.awt.font.*;
import java.util.Random;
/**
A 'bouncing balls' animation of <code>nballs</code> balls.
Each ball is controlled by a <code>Trajectory</code>.
*/
public class AnimatedBalls implements Animator
{
public AnimatedBalls(int nballs)
{
this.nballs = nballs;
}
public void oneFrame(Component comp,Graphics g)
{
int i;
if (balls == null) {
balls = new Ball[nballs];
for (i=0; i<nballs; i++)
balls[i] = new Ball(comp.getWidth(),comp.getHeight());
}
for (i=0; i<nballs; i++)
balls[i].moveAndDraw(comp,g,
comp.getWidth(),comp.getHeight());
}
private class Ball
{
public Ball(int framewidth,int frameheight)
{
width = 10.0 + r.nextDouble() * 20.0;
height = width;
t = new Trajectory(r,15.0,
(double)framewidth-width,
(double)frameheight-height);
double x = t.getX();
double y = t.getY();
e = new Ellipse2D.Double(x,y,width,height);
}
public void moveAndDraw(Component comp,
Graphics g,int framewidth,int frameheight)
{
Graphics2D g2 = (Graphics2D)g;
comp.setBackground(BG_COLOR);
g2.setPaint(INSIDE_COLOR);
g2.fill(e);
g2.setPaint(OUTSIDE_COLOR);
g2.draw(e);
Point2D p = t.nextPoint(
(double)framewidth-width,
(double)frameheight-height);
double x = p.getX();
double y = p.getY();
e.setFrameFromDiagonal(x,y,x+width,y+height);
}
private Ellipse2D e;
private double width,height;
private Trajectory t;
}
private Ball balls[] = null;
private int nballs = 20;
private static Random r = new Random();
private static final Color BG_COLOR = Color.WHITE;
private static final Color INSIDE_COLOR = Color.RED;
private static final Color OUTSIDE_COLOR = Color.BLACK;
}