☆課題☆

Java Applet/AWTについて学習し、Java Appletのオリジナルプログラムを作成し解説せよ。

オリジナルプログラム

import java.applet.Applet;
import java.awt.*;
public class rep6 extends Applet{
	int width;
	int height;
	Thre t[] = new Thre[10];
	public void init(){
		width=getSize().width;
		height=getSize().height;
	}
	public void start(){
		for(int i =0;i <10; i++){
			t[i] = new Thre(i);
			t[i].start();
		}
	}
	public void paint(Graphics g){
		g.setColor(Color.black);
		for(int i=0; i< 10; i++){
			g.fillOval(t[i].posx,t[i].posy,3,4);
			g.drawLine(t[i].sPlace, 0, t[i].posx, t[i].posy);
		}
	}

		class Thre extends Thread{
		int sPlace, shift = 10;
		int posx, posy;
		int i;
		public Thre(int i){
			sPlace = (int)(width * Math.random());
			this.i=i;
			
			posx = sPlace;
		}
			public void run(){
				Thread thre1=Thread.currentThread();
				while (t[i]== thre1) {
					repaint();
					posx += shift;
					if (posx >= width) {
						sPlace = (int)(width * Math.random());
						posx = sPlace;
						posy = 0;
					}
					posy += 20;
					if (posy >= height) {
						posy =0;
						sPlace = posx;
					}
				try{
					Thread.sleep(30);
				} catch (InterruptedException e) { }
			}
			}
		}
}

実行結果

流星群なのさ

考察

前回や前々回など前に説明した所は省きます。


widthとheightという変数を定義している。
Threの配列を10個作り、t[]で呼び出せるようにしておく。


initはブラウザを読み込んだときにする初期設定。
widthにアプレットの広さを取得して、入れている。
同じようにheightに高さを入れる。


ブラウザがアプレットを読み込んだときで処理の開始。
スレッドの開始。1〜10まで。


色を黒に指定。←いらないかも
fillOvalはintの引数で、左上端のオフセット座標、幅、高さ。
drawLineはintの引数で、始点座標(x1, y1)終点座標(x2, y2)。


ThreadをクラスThreが継承する。ローカル変数の宣言。


sPlaceに広さとランダム変数を掛けたものを入れている。
この関数のiに上のiを入れている。


現在のスレッドをthre1とする。
t[i]とthre1が同じのとき動き続ける。
なお違う時はないので永遠に動く。
こういう風に書くべきなのかわからない…。
まあサンプルどうりに。
再描写し続ける。


もしposxが広さを超えたらposxに広さとランダム変数を掛けたものを入れる。
そしてposyに0をいれて初期化する。
もしposyが高さを超えたらposyに0を入れて初期化する。
sPlaceにposxをいれてランダムに出力する。

スレッドのスリープ30ミリ秒に中断した時のための例外処理をしている。

感想

アプレットの処理の順番がなんかアプリケーションと違うから少しやりにくかった。
今回の課題をやるために1から勉強をし直した。
だけど結局1からは作れず、参考プログラムと同じ感じで書いた。
ある程度簡単なプログラムなら完全に自分で作れるようになりたい。自分の書き方を身につけたい。と思う。