Tuesday, November 4, 2008

BallAnimation

import java.awt.*;
import java.applet.*;

public class BallAnimation
extends Applet implements Runnable {

Thread animThread;
int ballX = 0;
int ballDirection = 0;

public void start() {
if (animThread == null) {
animThread = new Thread(this);
animThread.start();
}
}

public void stop() {
animThread.stop();
animThread = null;
}

public void run() {
while (true) {
moveBall();
delay(100);
}
}

private void delay(int miliSeconds) {
try {
Thread.sleep(miliSeconds);
} catch (Exception e) {
System.out.println("Sleep error !");
}
}

private void moveBall() {
if (ballDirection == 0) {
ballX++;
if (ballX > 100) {
ballDirection = 1;
ballX = 100;
}
} else {
ballX--;
if (ballX <= 0) {
ballDirection = 0;
ballX = 0;
}
}
repaint();
}
public void paint(Graphics g) {
g.setXORMode(getBackground());
g.fillRect(40, 10, 40, 40);
g.fillOval(ballX, 0, 30, 30);
}
}