放射円を描く


ループを利用し,放射円を描く。


*最初の図形は,コードをいろいろ書いているうちにこんなのが出来てしまった。消すのがもったいないので,そのまま残す。

Java Applet

ソースコード

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

public class ja04c extends Applet implements Runnable
{
  int xpos1,ypos1,xpos2,ypos2,xpos3,ypos3;  //放射円の左上のxy座標
  int r = 5;      //円の半径
  int t;          //放射する円の幅(直径)
  int n = 1;      //拡大する放射円の,半径の増分
  Image of;       //オフスクリーン用のイメージ
  Graphics ofg;   //オフスクリーン用のイメージのGraphicsオブジェクト
  Thread td;      //スレッド

  public void init(){
    setBackground(Color.white);	  	//Appletの背景色を白色に設定
    of = createImage(size().width,size().height); //オフスクリーン用のイメージの作成
    ofg = of.getGraphics();   	//オフスクリーン用のイメージのGraphicsオブジェクトを取得
	}

  public void paint(Graphics g){
    ofg.setColor(this.getBackground());   //全体を背景色で塗り潰す
    ofg.fillRect(0,0,size().width,size().height);

    for(int i = 0;i < 24;i++){  //(付録)以下のコードで,こんな図形ができてしまった。
      ofg.setColor(new Color(i * 8,i * 3,i * 10));
      xpos1 = 50 - 2 * i;
      ypos1 = 50 - 2 * i;
      t = 2 * (r + 2 * i);            	//放射円の幅(直径)
      ofg.drawOval(xpos1,ypos1,t,t);  	//オフスクリーンに描画
    }

    for(int i = 0;i < 10;i++){    	//放射円(固定)
      ofg.setColor(new Color(i * 15,i * 25,i * 5));
      xpos2 = 170 - 5 * i;    		//円の左上のxy座標
      ypos2 = 50 - 5 * i;
      t = 2 * (r + 5 * i);    		//放射円の幅(直径)
      ofg.drawOval(xpos2,ypos2,t,t);  	//オフスクリーンに描画
    }

    for(int i = 0;i < n;i++){     	//0.3秒間隔で拡大する放射円
      ofg.setColor(new Color(i * 19,i * 16,i * 3));
      xpos3 = 300 - 5 * i;    		//円の左上のxy座標
      ypos3 = 65 - 5 * i;
      t = 2 * (r + 5 * i);    		//放射円の幅(直径)
      ofg.drawOval(xpos3,ypos3,t,t);  	//オフスクリーンに描画
    }

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

  public void update(Graphics g){
    paint(g);
  }

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

  public void run(){
    while(true){
      try{
        n += 1;           	//拡大する円の増分
        if(n > 15)n = 1;  	//一定以上になると,デフォルトの 1 に戻す
        repaint();
        Thread.sleep(300);    	//0.3秒間隔でスレッドを実行
      }catch(InterruptedException e){stop();}
    }
  }

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

末尾