図形アニメーション(バウンドする円図形)


スレッドで円図形を移動さす。Applet内をクリックすれば,スレッドの一時停止/再開を切り替えできる。

*オフスクリーンの利用
*クリッピング領域を指定して再描画

Java Applet

ソースコード

import java.applet.*;
import java.awt.*;

public class ja31 extends Applet implements Runnable
{
  int xpos = 50,ypos = 50;  	//円図形の描画xy座標
  int r = 30;               	//円の直径
  int dx = 8,dy = 5;        	//移動量
  int w,h;      		//Appletの幅と高さ
  Image of;     		//オフスクリーンイメージ
  Graphics ofg; 		//オフスクリーンイメージのGraphicsオブジェクト
  Thread td;    		//スレッド
  boolean flag = true; 		//スレッドの停止/再開に利用するフラグ

  public void init(){
    w = size().width;   	//Appletのサイズを取得
    h = size().height;
    setBackground(Color.yellow);  //Appletの背景色
    of = this.createImage(w,h);   //オフスクリーン領域を作成
    ofg = of.getGraphics();   	//作成したオフスクリーンのGraphicsオブジェクトを獲得
  }

  public void paint(Graphics g){
    ofg.setColor(this.getBackground());   //オフスクリーンイメージをクリア(背景色で塗り潰す)
    ofg.fillRect(0,0,w,h);
    ofg.setColor(Color.red);
    ofg.fillOval(xpos,ypos,r,r);    	//オフスクリーンに円図形を描画

    g.drawImage(of,0,0,this);   	//オフスクリーンイメージを画面に描画
  }

  public void Update(Graphics g){   	//Update()のオーバーライド
    paint(g);
  }

  public void start(){
    if(td == null){
      td = new Thread(this);
      td.start();
    }
  }

  public void run(){
    while(true){
      if((xpos + r > w) || (xpos + dx < 0))dx = -dx;//円がAppletの左右端に達した時,移動量の符号を反転
      if((ypos + r > h) || (ypos + dy < 0))dy = -dy;//円がAppletの上下端に達した時,移動量の符号を反転
      xpos += dx;   //円の描画座標を移動量分だけ変える
      ypos += dy;

      repaint(xpos - dx,ypos - dy,r,r);
      repaint(xpos,ypos,r,r);
        //引数に,描画開始位置のxy座標と幅,高さを指定すれば,その領域だけが再描画される。
        //そのため,描画が速くなり,チラツキも抑えれる(クリッピング領域を指定した再描画)。
      try{
        Thread.sleep(100);    //0.1秒間隔で実行
      }catch(InterruptedException e){}
    }
  }

  public void stop(){
    if (td != null){
			td.stop();
			td = null;
		}
  }

  public boolean mouseDown(Event e,int x,int y){
    if(flag)td.suspend();		//スレッドを一時停止
	  else td.resume();		//スレッドを再開する
	  flag = !flag; 		//boolean型変数flagの真偽を反転
	  return true;
  }
}

末尾