The following is a java applet modeled after the classic 'bouncing ball' stuff like Pong that I used to write in Basic as a kid.

Of course, this assumes that all the collisions with the walls are elastic, and that there is no gravity. I will leave these minor imperfections to be addressed in a future release.

Anyway, my main objective here was to learn about Threads, and about how to read parameters passed to an applet, and about how to get information about the size of a string in graphic coordinates. I'm basically happy with the adventure this little exercise put me through.

I had been thinking that I could put all the string length/width adjustments into the initialization, but they are not known until graphics are being painted.

 *  BouncingHelloWorld
 *  Kevin Little 2/18/98
import java.applet.Applet;
import java.awt.Graphics;
import java.lang.Thread;
import java.awt.Font;
import java.awt.FontMetrics;

public class BouncingHelloWorld extends Applet implements Runnable {
    Thread engine = null;
    static int i,iv,j,jv,i0,j0,iw,jw;
    String s="Hello World!";  

    public void init() { 
        try {
        } catch (Exception e) {
        // huh?
                iw=800; jw=100;
        i=iw/2; j=jw/2; iv=iw/97; jv=jw/17;
    public void start() {
        if (engine == null) {
            engine = new Thread(this);
    public void stop() {
        if (engine != null && engine.isAlive()) engine.stop();
        engine = null;
    public void run() {
        Thread me = Thread.currentThread();
        while (engine == me) {
            try {
            } catch (InterruptedException e){
                // the VM doesn't want us to sleep anymore,
                // so get back to work

public void paint(Graphics g) {
            Font font = g.getFont();
            FontMetrics fontMetrics = g.getFontMetrics();
            int sheight = fontMetrics.getHeight();
            int swidth = fontMetrics.stringWidth(s);

            i=i+iv; j=j+jv;
            if ((iiw-swidth)) iv=-iv;
            if ((jjw)) jv=-jv;
            showStatus("Coordinates i= " + i + ", j=" + j);
Make your own free website on