| 3個のPanelクラスを作成し,それぞれ独立してスレッドを同時に実行。 |
import java.applet.*;
import java.awt.*;
public class ja203 extends Applet
{
ja203Panel P1,P2,P3; //ユーザー定義クラスja203Panelのインスタンスを3個
public void init(){
setLayout(new GridLayout(3,1,0,0)); //3行1列のGridLayoutマネージャーを設定
P1 = new ja203Panel(); //ja203Panelクラスのインスタンスを生成
P2 = new ja203Panel();
P3 = new ja203Panel();
add(P1); //インスタンスをAppletに配置する
add(P2);
add(P3);
P1.resize(300,100); //インスタンスのサイズを設定
P2.resize(300,100);
P3.resize(300,100);
P1.init(); //各インスタンスでja203Panelクラスのinit()メソッドを呼び出す
P2.init();
P3.init();
}
}
class ja203Panel extends Panel implements Runnable
{ //Runnableインターフェイスを実装し,Panelクラスを継承したクラスの定義。
int w,h; //パネルの幅と高さ
final int n = 5; //一度に表示する直線の数
ja201Line jline[] = new ja201Line[n]; //ja201lineクラスのインスタンス配列
Thread paThread; //スレッド
public void init(){
Dimension d = size(); //パネルの幅と高さを取得
w = d.width;
h = d.height;
setBackground(Color.black); //パネルの背景色を黒色に設定
paThread = new Thread(this); //スレッドを生成
int i;
for(i=0;i<n;i+=1){
jline[i] = new ja201Line(i); //ja201Lineのインスタンス配列を生成する
}
paThread.start(); //run()メソッドを呼び,スレッドを開始
}
public void run(){
while(true){
repaint();
try{
Thread.sleep(200); //0,2秒間隔でスレッドを実行
}catch(InterruptedException e){}
}
}
public void paint(Graphics g){
int i;
for(i=0;i<n;i+=1){ //n個数の直線を描画
jline[i].lineXY(w,h);
jline[i].paint(g);
}
}
}
class ja201Line
{
double x1,y1,x2,y2; //直線の開始位置と終了位置のxy座標
Color c;
Color linec[] ={Color.pink,Color.orange,Color.yellow,Color.green,Color.magenta};
public ja201Line(int i){ //コンストラクタ
c = linec[i]; //色配列から色を取得する
}
void lineXY(int w,int h){ //直線の開始位置と終了位置のxy座標をランダムに設定
x1 = (double)w * Math.random();
y1 = (double)h * Math.random();
x2 = (double)w * Math.random();
y2 = (double)h * Math.random();
}
void paint(Graphics g){
g.setColor(c);
g.drawLine((int)x1,(int)y1,(int)x2,(int)y2);
}
}
標準