import java.awt.*; import java.applet.*; import java.awt.event.*; /** * Animation in Java Article Series * * Source code provided by Heaton Research, Inc. * http://www.heatonresearch.com/ * Copyright 2005 by Heaton Research, Inc. * * This source code is distributed under a Limited GNU Public * License (LGPL). * * This is a very basic class to demonstrate the use of the * BasicAnimate class. This class shows a white ball that * bounces around the applet. * * @author Jeff Heaton(http://www.jeffheaton.com) * @version 1.0 */ public class BouncingBall extends BasicAnimate { /** * When this class is ran as an application, how wide should it be. */ public static final int IDEAL_WIDTH = 640; /** * When this class is ran as an application, how tall should it be. */ public static final int IDEAL_HEIGHT = 480; /** * What is the size of the bouncing ball. */ public final int SIZE = 32; /** * What is the current x-coordinate of the ball. */ private int x = 0; /** * What is the current y coordinate of the ball. */ private int y = 0; /** * What is the current x-direction of the ball, 1=right, -1=left */ private int dx = 1; /** * What is the current y-direction of the ball, 1=down, -1=Up */ private int dy = 1; /** * What is the width of the page that we should check, takes into * account how wide the ball is. */ private int checkWidth; /** * What is the height of the page that we should check, takes into * account how tall the ball is. */ private int checkHeight; /** * This method sets up the bouncing ball example. * */ public void init() { super.init(); checkWidth = getWidth() - SIZE; checkHeight = getHeight() - SIZE; setPulseLength(10); } /** * This method renders each frame of the bouncing ball. * * @param g The off-screen graphics object to paint to. */ public void paintOffscreen(Graphics g) { super.paintOffscreen(g); x += dx; y += dy; g.setColor(Color.WHITE); g.fillOval(x, y, SIZE, SIZE); // bounce if needed if ((x > checkWidth) || (x < 0)) dx = -dx; if ((y > checkHeight) || (y < 0)) dy = -dy; } /** * The main method is called when the class is to be ran * as a Java application. This method creates a frame and * attaches the applet to the frame. * * @param args Not used. */ public static void main(String args[]) { Applet applet = new BouncingBall(); Frame frame = new Frame(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.add(applet); frame.setSize(IDEAL_WIDTH, IDEAL_HEIGHT); frame.show(); applet.init(); } }