/*----------------------------------------------- ex12_4.java アプレット:スレッドを使う3(スレッド一時停止) ------------------------------------------------*/ import java.applet.*; import java.awt.*; import java.util.Random; /* */ public class ex12_4 extends Applet implements Runnable { Thread thd = null; int x, y, wid, hei, red, grn, blu, k; Color col; Random rnd; public void init() { // 初期化処理 x = 10; y = 10; wid = 40; hei = 40; k = 0; red = 255; grn = 0; blu = 0; col = new Color(red, grn, blu); rnd = new Random(); thd = new Thread(this); // 新しいスレッドを作る thd.start(); // スレッド開始 } public void update(Graphics g) { // 再描画の説きに背景クリアをしない場合はこのメソッドを使う paint(g); } public void paint(Graphics g) { // 描画処理 g.setColor(col); g.fillRect(x, y, wid, hei); } public void run() { // スレッド開始したときに呼び出されるメソッド while (true) { // 無限ループ x = rnd.nextInt(150); y = rnd.nextInt(150); wid += 10 * Math.cos(Math.PI/4*k); hei += 10 * Math.sin(Math.PI/4*k); k++; red = rnd.nextInt(255); grn = rnd.nextInt(255); blu = rnd.nextInt(255); col = new Color(red, grn, blu); repaint(); // アプレット強制再描画メソッド(結果としてpaint()が実行される) // スレッドを一時停止(停止時間:400ミリ秒) try { thd.sleep(400); } catch (InterruptedException e) { } } } }