/* $Id: AnimationSample.java,v 1.4 1999/08/11 16:26:02 gjb Exp $ ---------------------------------------------------------------------- yasuhara@cs.washington.edu, badros@cs.washington.edu CSE 341, Assignment 6 August 1999 */ import java.awt.*; import java.awt.event.*; import AnimationApplet; /** AnimationSample is a demonstration applet exercising the AnimationApplet framework. */ public class AnimationSample extends AnimationApplet { ///////////////////////// variables Ball ball; // default window title, size when running from main static protected final String mainWindowTitle = "AnimationSample"; static protected final int defaultWidth = 300, defaultHeight = 300; ///////////////////////// methods // // constructors // public AnimationSample() { super(); initFields(); } public AnimationSample(int w, int h) { super(w,h); initFields(); } private void initFields() { ball = new Ball(width/2, height/2, 5, Color.red, -2, 3); } // // AnimationApplet overrides // public void prepareNextFrame() { ball.move(); if (ball.x < 0 || ball.x > width) { ball.dx = -ball.dx; if (ball.x < 0) ball.x = 0; else ball.x = width; } if (ball.y < 0 || ball.y > height) { ball.dy = -ball.dy; if (ball.y < 0) ball.y = 0; else ball.y = height; } ball.accelerate(0, 1); } public void drawNextFrame(Graphics g) { g.setColor(getBackground()); g.fillRect(0, 0, width, height); ball.paint(g); } public void keyPressed(KeyEvent ke) { super.keyPressed(ke); switch (ke.getKeyChar()) { case '+': sleepTime += 10; if (debug) System.out.println("sleepTime = " + sleepTime); break; case '-': if (sleepTime > 10) sleepTime -= 10; if (debug) System.out.println("sleepTime = " + sleepTime); break; } } ///////////////////////// main public static void main(String[] args) { AnimationSample applet = new AnimationSample(defaultWidth,defaultHeight); applet.init(); applet.startInFrame(); } public void startInFrame() { Frame frame = new Frame(mainWindowTitle); frame.setSize(defaultWidth, defaultHeight); frame.add("Center", this); frame.show(); start(); } } class Ball { // position, radius, velocity components, color public int x, y, radius, dx, dy; public Color color; public Ball(int x, int y, int radius, Color color, int dx, int dy) { this.x = x; this.y = y; this.radius = radius; this.color = color; this.dx = dx; this.dy = dy; } public void paint(Graphics g) { g.setColor(color); g.fillOval(x - radius, y - radius, radius * 2, radius * 2); } public void move() { x += dx; y += dy; //System.out.println(x + ", " + y); } public void accelerate(int ddx, int ddy) { dx += ddx; dy += ddy; } } /* Local Variables: */ /* tab-width: 4 */ /* c-basic-offset: 4 */ /* End: */