import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Ori extends Applet implements ActionListener,Runnable{
MyCanvas c1; //(1):各メソッドで使用する変数、クラスのインスタンスを
Button btn1,btn2; // 宣言.
boolean flag;
int x,y,ax,ay;
Color c;
char c0;
Font f;
int count = 0;
public void init() { //(2):initメソッドの実行内容を設定.
flag = false; // ボタンの配置やメソッドのフィールドの初期化
x = 10; // を行う.Javaアプリケーションでのコンストラクタ
y = 10; // と同じ働き.
Random r1 = new Random();
ax = r1.nextInt(21)-10;
ay = r1.nextInt(21)-10;
int r = r1.nextInt(255);
int g = r1.nextInt(255);
int b = r1.nextInt(255);
c = new Color(r,g,b);
c0 = (char)(r1.nextInt(26)+65);
f = new Font("Dialog",Font.BOLD,r1.nextInt(24)+24);
this.setLayout(null);
c1 = new MyCanvas();
this.add(c1); c1.setBounds(0,0,500,150);
btn1 = new Button("Fast!");
this.add(btn1); btn1.setBounds(180,240,70,30);
btn2 = new Button("Freeze!");
this.add(btn2); btn2.setBounds(260,240,70,30);
btn1.addActionListener(this);
btn2.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btn1){ //(3):ボタンをクリックした際の
this.count++; // プログラムの反応を設定.
this.repaint(); // btn1のボタンを押すと、start()
this.start(); // メソッドの再実行とrepaint()の
}else{ // 実行が行われる.
doStop();
this.count = 0;
}
}
public void start(){ //(4):アプレットの開始.開始と同時に
Thread t1 = new Thread(this);// スレッドの生成と実行を始める.
t1.start();
}
public void doStop() { //(5):スレッドを停止する際に使用するメソッド。
flag = false; // run()メソッド内の動作条件フラグの
} // 切り換えをする。
public void run() { //(6):スレッドのrun()メソッドの定義.条件フラグが
flag = true; // 真の間、クラスMyCanvasで生成したGUI部品上で
while(flag){ // 描画するテキストの生成と、テキストを動かす
move(); // 際に必要な座標等の設定を行い、それをGUI
c1.x = x; // コンポーネントのCanvas上で動かす.
c1.y = y;
c1.setColor(c);
c1.setChar(c0);
c1.setFont(f);
c1.repaint();
try { //(7):スレッドの実行速度の調整.100ミリ秒単位で
Thread.sleep(100); //スレッドを一時停止し、テキストの移動の
}catch(Exception e) {} //スピードを調整.
}
}
public void move(){ //(8):テキストの移動先の座標を設定するメソッド.
x += ax; // 動作する場所となるGUI部品の幅と長さを
y += ay; // 引数として取る。
if(x < 0) {
x = 0;
ax *= -1;
}
if(x > c1.getSize().width) {
x = c1.getSize().width;
ax *= -1;
}
if (y < 0) {
y = 0;
ay *= -1;
}
if (y > c1.getSize().height) {
y = c1.getSize().height;
ay *= -1;
}
}
public void stop() { //アプレット終了時の処理.あっても無くても良かった
this.count = 0; //かもしれない.
}
public void paint(Graphics gs) {
gs.drawString("Move Speed: +" + (new Integer(count)).toString(),30,270);
} //(9):スタートボタンのクリック回数を表示するメソッド.
// 生成したスレッドとは独立して動いています.
class MyCanvas extends Canvas{ //(10):スレッドの実行対象になるGUI部品
int x,y; // のクラス.移動テキストの生成と、
Color c; // 移動テキストを表示するGUIコンポーネントの
String s; // 生成を行う.
Font f;
public void setColor(Color c1) {
c = c1;
}
public void setChar(char c1){
s = "" + c1;
}
public void setFont(Font f1) {
f = f1;
}
public void paint (Graphics g) {
if (c != null) {
g.setColor(c);
g.setFont(f);
g.drawString(s,x,y);
}
}
}
} |