| 2重多角形を描く。 translate()で座標原点をランダムに変更することで,揺れ動く。 |
import java.applet.*;
import java.awt.*;
public class ja04e extends Applet implements Runnable
{
int w,h; //Appletの幅と高さ
int x = 0; //座標系の原点のxy座標
int y = 0;
int fg = 1; //描画色を変更するために利用するフラグ
Thread td = null; //スレッド
public void init(){
setBackground(Color.black); //Appletの背景色を黒色に設定
w = size().width; //Appletのサイズを取得
h = size().height;
}
public void paint(Graphics g){
Graphics g2 = g.create(); //Graphicsオブジェクトをコピー
//このコピーしたグラフイックスコンテキストの原点座標をtranslate()で変更する。
if(fg == 1 || fg == 2 || fg == 3){ //フラグ変数fgが1,2,3の時だけ文字列を描画
g2.setFont(new Font("TimesRoman",Font.BOLD,30));
if(fg == 1)g2.setColor(Color.pink); //fgにより描画色をピンク,緑,赤に変更
if(fg == 2)g2.setColor(Color.green);
if(fg == 3)g2.setColor(Color.red);
FontMetrics fm = g2.getFontMetrics();
String s = "Kodayan HomePage";
g2.drawString(s,(w - fm.stringWidth(s))/2,h*3/4 - h/10);//Appletのセンターに描画
}
if(fg == 1){ //フラグ変数fgにより多角形の描画色を分岐する
g2.setColor(Color.red);
fg = 2;
}else if(fg == 2){
g2.setColor(Color.yellow);
fg = 3;
}else if(fg == 3){
g2.setColor(Color.white);
fg = 4;
}else if(fg == 4){
g2.setColor(Color.black);
fg = 5;
}else{
g2.setColor(Color.blue);
fg = 1;
}
//2重多角形を描画するため,座標を2ピクセルずらして2回 drawPolygon()する。
g2.translate(x,y); //描画座標の原点(左上のxy座標)を変更する
int xpos1[]={10,10,w/2,285,285,w/2,10}; //多角形の頂点(x座標)の配列
int ypos1[]={h/4,h*3/4,85,h*3/4,h/4,15,h/4}; //多角形の頂点(y座標)の配列
g2.drawPolygon(xpos1,ypos1,7); //多角形の描画
int xpos2[]={12,12,w/2+2,287,287,w/2+2,12}; //2番目の目の多角形の頂点の配列
int ypos2[]={h/4+2,h*3/4+2,87,h*3/4+2,h/4+2,17,h/4+2};
g2.drawPolygon(xpos2,ypos2,7); //2番目の多角形の描画
g2.dispose(); //コピーしたGraphicsオブジェクトを破棄し,システムリソースを解放する
//translate()のx,yを-7〜7の範囲でランダムに変化さす
x += (int)(Math.random() *15) - 7; //0〜14の整数値を得,それから7を引く
y += (int)(Math.random() *15) - 7;
if(x < -10)x = 0; //原点座標x,yが大きくズレないように調整
if(x > 10)x = 0;
if(y < -10)y = 0;
if(y > 10)y = 0;
}
public void start(){
if(td == null){
td = new Thread(this); //Treadオブジェクトの生成
td.start(); //スレッドの実行開始
}
}
public void run(){
while (true) //繰り返し制御文
{
try
{
repaint(); //paintメソッドを呼び出し再描画
Thread.sleep(200); //0.2秒だけスレッドを停止する。
}
catch (InterruptedException e)
{
stop(); //スレッドの実行を中止
}
}
}
public void stop(){
if (td != null){
td.stop();
td = null;
}
}
}
末尾