Ex14_2
/*-------------
Ex14_2.java
アニメーション
--------------*/
package jp_package;
import java.applet.*;
import java.awt.*;
public class Ex14_2 extends Applet implements Runnable {
int x, y, width, height, num; // 位置 (x, y), 幅 width, 高さ height
int red, grn, blu; // 3色用変数
Color col; // 色クラス
Thread thd = null; // スレッド
public void init() { // 初期化
this.setSize(310, 310);
x = 5; y = 5; // 正方形の初期位置(x,y)設定
width = 29; height = 29; // 正方形の幅と高さ設定
num = 0; // 描画の回数を制御する変数
red = 125; grn = 255; blu = 125; // 3色の設定
col = new Color(red, grn, blu); // 3色を混ぜて色をつくる
thd = new Thread(this); // スレッドをつくる
thd.start(); // スレッド開始
}
public void paint(Graphics g) {
g.setColor(col); // 色を設定
for (int i=0; i < num; i++) { // 横方向に動かすためのループ
for (int j = 0; j < num; j++) { // 縦方向に動かすためのループ
if (i+j==num+5 || i+j==num+2 || i+j==num-1 || i+j==num-4 || i+j == num-7) {
g.fillRect(x+30*i, y+30*j, width, height); // x軸 30*i, y軸 30*j ずらしながら矩形を描く
} else {
g.drawRect(x+30*i, y+30*j, width, height); // x軸 30*i, y軸 30*j ずらしながら矩形を描く
}
}
}
}
public void run() {
while (true) {
while (num < 10) {
num++;
repaint(); // 再描画
try { // 例外処理
thd.sleep(500); // スレッドスリープ(500ミリ秒)
} catch (InterruptedException e) {
}
}
while (num > 0) {
num--;
repaint();
try { // 例外処理
thd.sleep(100); // スレッドスリープ(500ミリ秒)
} catch (InterruptedException e) {
}
}
red = (red + 50) % 255; // 赤を少し変えるよ
grn = (grn + 60) % 255; // 緑を少し変えるよ
blu = (blu + 70) % 255; // 青を少し変えるよ
col = new Color(red, grn, blu); // 色を作り直すよ
}
}
}