import java.applet.*;
import java.util.*;
import java.awt.*;
/*
<applet code="ClockApplet" width=120 height=20>
</applet>
*/
public class ClockApplet extends Applet implements Runnable{
Image imgArray[]; /* 画像の配列(0〜9) */
Image imgColon; /* コロン(:)の画像 */
ClockCanvas canvas; /* キャンバス */
Thread t; /* スレッド */
public void init(){
/* 画像読み込み */
getImages();
/* コンポーネントの作成と追加 */
setLayout(new GridLayout());
canvas = new ClockCanvas();
canvas.setImages(imgArray, imgColon);
add(canvas);
/* スレッド開始 */
t = new Thread(this);
t.start();
}
/* パラメータータグを読み込む */
public void getImages(){
try{
/* 画像を格納する配列を作る */
imgArray = new Image[10];
/* 画像を取得する */
for( int i = 0 ; i <= imgArray.length - 1 ; i++ ){
imgArray[i] = getImage(getDocumentBase(), "applet/img" + i + ".gif");
/*↑jarファイルをサブディレクトリに入れる場合は注意*/
}
imgColon = getImage(getDocumentBase(), "imgcolon.gif");
}catch(Exception e){
System.err.println("Failed to load the images");
}
}
/* スレッド */
public void run(){
while(true){
canvas.repaint();
try{
synchronized(t){
t.wait(500);
}
}catch(Exception e){
System.err.println(e);
}
}
}
}
/* クロックキャンバスクラス*/
class ClockCanvas extends Canvas{
Image imgNumber[];
Image imgColon;
/* 画像をクラスフィールドにセットします */
public void setImages(Image imgNumber[], Image imgColon){
/* 本来ならば画像の枚数、nullがないなどのチェックをした方がよいが、割愛 */
this.imgNumber = imgNumber;
this.imgColon = imgColon;
}
/* 画像を表示させるメソッド */
public void paint(Graphics g){
/* まだ画像が登録されていなければ帰る */
if( imgNumber == null || imgColon == null )
return;
/* 時間を取得 */
Calendar c = Calendar.getInstance();
int x = 0;
int h10 = c.get(Calendar.HOUR_OF_DAY) / 10;
int h1 = c.get(Calendar.HOUR_OF_DAY) % 10;
int m10 = c.get(Calendar.MINUTE) / 10;
int m1 = c.get(Calendar.MINUTE) % 10;
int s10 = c.get(Calendar.SECOND) / 10;
int s1 = c.get(Calendar.SECOND) % 10;
/* キャンバスのサイズを取得する */
Dimension d = getSize();
/* 画像を表示 */
g.drawImage(imgNumber[h10], x, 0, Color.white, this);
x = x + imgNumber[h10].getWidth(this);
g.drawImage(imgNumber[h1], x, 0, Color.white, this);
x = x + imgNumber[h1].getWidth(this);
g.drawImage(imgColon, x, 0, Color.white, this);
x = x + imgColon.getWidth(this);
g.drawImage(imgNumber[m10], x, 0, Color.white, this);
x = x + imgNumber[m10].getWidth(this);
g.drawImage(imgNumber[m1], x, 0, Color.white, this);
x = x + imgNumber[m1].getWidth(this);
g.drawImage(imgColon, x, 0, Color.white, this);
x = x + imgColon.getWidth(this);
g.drawImage(imgNumber[s10], x, 0, Color.white, this);
x = x + imgNumber[s10].getWidth(this);
g.drawImage(imgNumber[s1], x, 0, Color.white, this);
}
}
|