import java.applet.Applet;
import java.awt.Image;
import java.awt.Graphics;
import java.awt.Dimension;
import java.awt.Color;
public class GuruGuru1 extends Applet implements Runnable {
int x, y, r, h, m;
boolean fl;
Thread th;
Dimension d;
Image bufImg;
Graphics bufGrp;
public void init() {
x = 100; // 円の中心 x座標
y = 100; // 円の中心 y座標
r = 20; // 円の半径
h = 3; // 円の進行方向 1:左上 2:右上 3:右下 4:左下
m = 1; // 移動距離
th = null;
fl = true;
d = this.getSize(); // アプレット領域の縦横サイズ
bufImg = this.createImage(d.width, d.height); // バッファ用イメージ
bufGrp = bufImg.getGraphics(); // バッファ用グラフィックス
}
public void start() {
if (th == null) {
th = new Thread(this); // スレッドを作る
th.start();
}
}
public void run() {
try {
while (true) {
switch (h) {
case 1:
x -= m; y -= m;
break;
case 2:
x += m; y -= m;
break;
case 3:
x += m; y += m;
break;
case 4:
x -= m; y += m;
break;
}
// 壁に当たった時の判別
if (x >= d.width - r) {
if (h == 2) h = 1;
if (h == 3) h = 4;
}
if (x <= 0) {
if (h == 1) h = 2;
if (h == 4) h = 3;
}
if (y >= d.height - r) {
if (h == 4) h = 1;
if (h == 3) h = 2;
}
if (y <= 0) {
if (h == 2) h = 3;
if (h == 1) h = 4;
}
repaint(); // 再描画する update() → repaint() と呼ばれる
Thread.sleep(10); // 眠る
}
} catch (InterruptedException err) {}
}
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
// 最初にバッファに書き込む
bufGrp.setColor(Color.white);
bufGrp.fillRect(0, 0, d.width, d.height);
bufGrp.setColor(Color.blue);
bufGrp.fillOval(x , y , r, r);
// バッファを Applet 領域に書き出す。ちらつかない。
g.drawImage(bufImg, 0, 0, this);
}
}
面倒くさいので詳細はコメント読んでちょ。