import java.awt.*; import java.util.*; public class Tokei extends java.applet.Applet implements Runnable { Thread kicker = null; // アニメーションのためのスレッド変数 int hour,min,sec,year,month,day; public void init() { } public void start() { /* スレッドの作成と起動 */ kicker=new Thread(this); kicker.start(); } public void stop() { /* スレッドを止める */ kicker = null; } public void run() { /* 実行中のスレッドをチェック */ Thread thisThread = Thread.currentThread(); //自分のスレッドを取得 Calendar calendar = new GregorianCalendar(); //カレンダーを取得 /* ずっと繰り返し */ while( kicker == thisThread) { Date NowTime = new Date(); calendar.setTime(NowTime); //今の時間をセット hour=calendar.get(Calendar.HOUR_OF_DAY); //時を習得 min=calendar.get(Calendar.MINUTE); //分を習得 sec=calendar.get(Calendar.SECOND); //秒を習得 day=calendar.get(Calendar.DATE); //日を習得 month=calendar.get(Calendar.MONTH)+1; //月を取得(0から始まるので+1する) year=calendar.get(Calendar.YEAR); //年を取得 /* 再描画 */ repaint(); try { /* スレッドのお休み時間=表示時間の設定 */ thisThread.sleep(500); } catch (InterruptedException e){} } } public void paint(Graphics g) { update(g); } public void update(Graphics g) { g.setFont(new Font("TimesRoman",Font.BOLD,16)); //フォントを設定 g.setColor(Color.black); //色を設定 g.fillRect(0,0,160,100); //四角形を描写 g.setColor(Color.white); //文字の色を設定 g.drawString(year+"/"+month+"/"+day, 30, 30); //年月日を描写 g.drawString(hour + ":" + min + ":" + sec, 45, 60); //時間を描写 } }
スレッドとは、プログラムの最小実行単位のことでアニメーションのようにグラフィックスを動かす場合や、ネットワーク通信時に待つ場合等に使われます。複数のスレッドを処理することをマルチスレッドといいます。
GregorianCalendarは世界のほとんどの地域で使用される標準的なカレンダーを提供するもので、日時を取得します。このアプレットは取得した情報から年月日と時間を表示するものです。
何を作っていいか分からず、試行錯誤した結果こんな物になりました。欲を言えば時間はアナログで表示してみたかったです。