デジタル時計


都市を選択すれば,その都市の現在時刻がデジタル表示される。 Java Appletです

ソースコード

import java.applet.*;
import java.awt.*;
import java.util.*;   		//Dateクラスが属する

public class ja03a extends Applet implements Runnable
{
  Date nowtime;   		//現在時刻を格納
  int width,height;    		//Appletのサイズ(横幅と高さ)
  Thread th;  //スレッド
  Choice ch = new Choice();  	//選択ボックスの作成
  int timesa = 0;   		//各都市の東京との時差 

  public void init(){
    width = size().width;   	//Appletのサイズを取得
    height = size().height;
    setLayout(null);        	//レイアウトマネージャーを使わない
    add(ch);
    ch.reshape(300,10,90,30);   //Choiceを指定位置に配置
    ch.addItem("東京");         //Choiceに都市名を登録
    ch.addItem("ロンドン");
    ch.addItem("パリ");
    ch.addItem("ニューヨーク");
    ch.addItem("香港");
    ch.addItem("モスクワ");
  }

  public void start(){
    if(th == null){
      th = new Thread(this);
      th.start();
    }
  }

  public void stop(){
    th.stop();
    th = null;
  }

  public void run(){
    while(th != null){
      repaint();
      try{
        Thread.sleep(1000); 		//1秒間隔でスレッドを実行
      }catch(InterruptedException e){}
    }
  }

  public void update(Graphics g){
    g.setColor(Color.orange); 		//orange色でApplet全体を塗り潰す
    g.fillRect(0,0,width,height);

    nowtime = new Date(); //現在時刻を取得
    int h = nowtime.getHours() + timesa;   //現在時刻から時間を取得し,各都市の時差を計算
    if(h < 0)h = 24 + h;    		//日付が変る場合の修正
    if(h > 24)h = h - 24;
    int m = nowtime.getMinutes(); 	//現在時刻から分を取得
    int s = nowtime.getSeconds(); 	//現在時刻から秒を取得

    String time;    			//時刻を格納する文字列
    if(h < 10)time = "0" + h; 		//1桁数値の場合,0を付ける
    else time = "" + h;
    if(m < 10)time += ":0" + m;
    else time += ":" + m;
    if(s < 10)time += ":0" + s;
    else time += ":" + s;

    g.setColor(Color.black);
    g.setFont(new Font("TimesRoman",Font.BOLD,height*3/2));//TimesRomanフォントを想定し,(h*3/2)ポイントを設定
    g.drawString(time,0,height); 	//時刻を表示
  }

  public boolean action(Event e,Object o){
    if(e.target instanceof Choice){	//各都市を選択した場合,東京との時差を設定
      if("東京".equals(o))timesa = 0;
      if("ロンドン".equals(o))timesa = -9;
      if("パリ".equals(o))timesa = -8;
      if("ニューヨーク".equals(o))timesa = -14;
      if("香港".equals(o))timesa = -1;
      if("モスクワ".equals(o))timesa = -6;
    }
    return true;
  }
}

末尾