// 2/23/2000 TYan // graphical version of balls import java.awt.*; class Ball { Color color; double pos; double velocity; // create a Ball with name n, position p, velocity v Ball(Color c, double p, double v) { color = c; pos = p; velocity = v; } // draw using specified scale factor void paint(Graphics g, double scale) { int diameter = (int) scale; g.setColor(color); g.fillOval((int) (scale*pos), diameter/2, diameter, diameter); } // move the ball with acceleration a, bouncing as appropriate void move(double a) { pos += velocity; if (pos < 0) { velocity = -velocity; pos = -pos; } velocity += a; } } class World1D extends Frame { double accel = -.2; double scale; int steps; // create a world of size w and scale factor s (hence, width w*s) // that draws t time steps public World1D(double w, int t, double s) { scale = s; steps = t; show(); // show; apparently needed to getInsets setSize(getInsets().left+getInsets().right+(int)(s*w), getInsets().top+getInsets().bottom+(int)(s*(1+t))); setBackground(Color.white); } // safely create and draw all the balls // NOTE: In Project 4, you do NOT want to (re)create molecules // each time you draw. synchronized public void mypaint(Graphics g) { Ball a = new Ball(Color.red, 15, 4); Ball b = new Ball(Color.green, 28, .5); Ball c = new Ball(Color.blue, 3,-2); g.translate(getInsets().left,getInsets().top); g.clearRect(0,0,getSize().width,getSize().height); for (int i = 0; i <= steps; i++) { g.translate(0,(int) scale); a.paint(g,scale); b.paint(g,scale); c.paint(g,scale); a.move(accel); b.move(accel); c.move(accel); } } // draw all the balls public void paint(Graphics g) { mypaint(g); } } public class graphics0 { public static void main(String[] args) { World1D w = new World1D(80,100,6); } }