/* Clock Applet
   JDK1.1対応版
                  Coded By.KeN    Mar 18,1997
*/

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Font;

// imprements Runnableでマルチスレッド対応にします
public class Clock extends java.applet.Applet implements Runnable {

  Thread clockdisplay; // Thread型の新しいスレッド
  Font fonts; // Font設定用オブジェクト

  public void init() {
    fonts = new Font( "TimesRoman", Font.BOLD, 24 ); // フォントの設定
  }

  public void paint( Graphics scr ) { // 表示メソッド
    // グレゴリオ暦のオブジェクト
    GregorianCalendar today = new GregorianCalendar
                              ( TimeZone.getTimeZone( "JST" ) );

    String hms = ""; // 表示用文字列変数

    scr.setFont( fonts ); // 設定したフォントを画面描画フォントに適用します
    scr.setColor( Color.blue ); // 描画色を青にします
    /* 画面に年月日の表示をします
        YEAR:年
        MONTH:月(1〜12)
        DAY_OF_MONTH:日(1〜31)
    */
    scr.drawString(today.get( Calendar.YEAR ) + "/" +
                   today.get( Calendar.MONTH ) + "/" + 
                   today.get( Calendar.DAY_OF_MONTH ),
                   20,25);

    if ( today.get( Calendar.HOUR_OF_DAY ) < 10 ) { // HOUR_OF_DAYは時(0〜23)
      hms += "0"; // 1桁の場合0を頭につけます
      }
    hms += today.get( Calendar.HOUR_OF_DAY ) + ":";
    if ( today.get( Calendar.MINUTE ) < 10 ) { // MINUTEは分(0〜59)
      hms += "0";
      }
    hms += today.get( Calendar.MINUTE ) + ":";
    if ( today.get( Calendar.SECOND ) < 10 ) { // SECONDは秒(0〜59)
      hms += "0";
      }
    hms += today.get( Calendar.SECOND );

    scr.drawString( hms, 20, 50 );   // 作成した時刻の文字列を表示します

    today = null;
  }

  public void start() { // アプレットが開始したら実行するメソッド
    if ( clockdisplay == null ) { // まだ設定していないなら
      clockdisplay = new Thread( this ); // run()の部分はこのクラスと同じもの
                                         // を使う新しいスレッドの宣言
      clockdisplay.start(); // スレッドの開始
    }
  }

  public void run() { // スレッドの実行部分
    while ( true ) { // 無限ループ
      try { Thread.currentThread().sleep( 1000 ); } // 1秒間待つ
        catch ( InterruptedException e ) // 何らかの事情で中断されたら
        { break; }                       // ここに来ます
      repaint(); // 画面の更新(画面消去後、paint()メソッドが実行されます)
    }
  }

  public void stop() { // スレッドのストップ
    if ( clockdisplay != null ) {
      clockdisplay.stop();
      clockdisplay = null;
    }
  }
}

