源代碼如下:
import java.awt.*;import java.applet.*;import java.util.Date; //這是Java中的低級實用工具包,可以處理時間等內(nèi)容。public class Applet1 extends Applet implements Runnable //有線程運行接口{Date timenow; //Date是一個時間定義與創(chuàng)建函數(shù).Clock myClock; //用戶自定義的類Thread clockthread=null; //設(shè)置一個線程public void start() //線程開始的類{if (clockthread==null) //如果線程為空,則{clockthread=new Thread (this); //開始新的線程clockthread.start(); //開始}}public void stop() //終止線程{clockthread.stop(); //終止線程,使它clockthread=null; //為空}public void run() //運行線程{while(true) //一個死循環(huán),條件永遠(yuǎn)都是真的。{repaint(); //重新繪制界面try{Thread.sleep(1000);} //讓線程沉睡1000毫秒,也就是一秒鐘catch(InterruptedException e){} //捕獲異常(也就是錯誤)}}public void paint(Graphics g){timenow=new Date(); //新的時間的獲得//獲得小時,分鐘,秒鐘myClock=new Clock(timenow.getHours (),timenow.getMinutes (),timenow.getSeconds ());g.drawString(timenow.toString(),25,240);//將它打印出來!myClock.show(g,100,100,100); //使面板顯示}}class Clock //用戶自定義的類開始,編譯后,它單獨成為一個CLASS文件{Clock(int hrs,int min,int sec) //類函數(shù)入口{hour=hrs%12; //將原始數(shù)據(jù)處理,得到小時minute=min; //將原始數(shù)據(jù)處理,得到分鐘second=sec; //將原始數(shù)據(jù)處理,得到小時}void show(Graphics g,int cx,int cy,int rad) //重新定義SHOW函數(shù){int hrs_len=(int)(rad*0.5), //時針的長度min_len=(int)(rad*0.6), //分鐘的長度sec_len=(int)(rad*0.9); //秒鐘的長度double theta;//畫出鐘面g.drawOval(cx-rad,cy-rad,rad*2,rad*2);//畫出時針theta=(double)(hour*60*60+minute*60+second)/43200.0*2.0*Math.PI ;drawNiddle(g,Color.blue,cx,cy,hrs_len,theta);//畫出分針theta=(double)(minute*60+second)/3600.0*2.0*Math.PI ;drawNiddle(g,Color.red,cx,cy,sec_len,theta);//畫出秒針theta=(double)(second)/60.0*2.0*Math.PI ;drawNiddle(g,Color.green ,cx,cy,sec_len,theta);}private void drawNiddle(Graphics g,Color c,int x,int y,int len,double theta){int ex=(int)(x+len*Math.sin(theta));int ey=(int)(y-len*Math.cos(theta));g.setColor (c);g.drawLine(x,y,ex,ey);}int hour,minute,second;}