Double-Buffered Bouncing Ball Program
[Up]
Source Code
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Image;
import java.applet.Applet;
public class DBall extends Applet implements Runnable {
Thread thr;
Image buffer;
Graphics GC;
int x = 20, y = 300, r = 7;
int vx = 5, vy = 0, a = 3;
double d = 0.88;
public void init() {
buffer = createImage(400, 400);
GC = buffer.getGraphics();
GC.setColor(Color.white);
GC.fillRect(0, 0, 400, 400);
GC.setColor(Color.blue);
GC.fillOval(50+x-r, 380-y+r, 2*r, 2*r);
}
public void start() {
if (thr == null) {
thr = new Thread(this);
thr.start();
}
}
public void run() {
while(true) {
repaint();
try{
Thread.sleep(50);
}
catch(InterruptedException e) { }
}
}
void calc() {
x += vx; y -= vy;
vy += a;
if (x > 300) {
x = 600-x; vx *= -1;
}
else if (x < 0) {
x *= -1; vx *= -1;
}
if (y < 0) {
y = (int)(-(double)y * d); vy = (int) (-(double) vy * d);
}
else if (y == 0 && vy == 0) {
x = 20; y = 300;
}
}
public void paint(Graphics g) {
update(g);
}
public void update(Graphics g) {
g.drawImage(buffer, 0, 0, this);
calc();
GC.setColor(Color.white);
GC.fillRect(0, 0, 400, 400);
GC.setColor(Color.blue);
GC.fillOval(50+x-r, 380-y+r, 2*r, 2*r);
}
public void stop() {
if (thr != null) {
thr.stop();
thr = null;
}
}
}
naniwa@rbt.his.fukui-u.ac.jp