| マルチスレッドを利用してアニメーションを表示。 Mouseクリックで,アニメーションの停止/再開を切り替えできる。 |
|
import java.applet.*;
import java.awt.*;
public class ja30 extends Applet implements Runnable{
Image pic[] = new Image[6]; //アニメーション用画像の配列
Thread ani; //スレッドオブジェクト
int n = 0; //配列画像の番号
boolean flag = true; //スレッドの動作状態を識別するフラグ
public void init(){
setBackground(Color.white); //Appletの背景色を黄色に設定
for(int i = 0;i < 6;i++){ //6枚のgifファイルを読み込む
pic[i] = getImage(getCodeBase(),"Sy" + i + ".gif");
}
}
public void start(){
if(ani == null){
ani = new Thread(this);
ani.start(); //ja30クラスのrun()メソッドを呼び出す
}
}
public void run(){
while(true){ //無限ループを繰り返す
if(n > 5) n = 0;
repaint(); //paint()メソッドを呼び出す
try{
Thread.sleep(1000); //1秒だけスレッドを停止する。
}catch (InterruptedException e){
}
n++; //配列画像の番号を1増やす
}
}
public void paint(Graphics g){
g.drawImage(pic[n],30,30,this); //画像の描画
}
public void stop(){
if(ani != null){
ani.stop();
ani = null;
}
}
public boolean mouseDown(Event evt,int x,int y){
if(flag){
ani.suspend(); //スレッドを一時停止
flag = false;
}else{
ani.resume(); //スレッドを再開する
flag = true;
}
return true;
}
}
末尾