編寫Applet小程序,通過在HTML文檔中接收參數(shù), 用不同顏色、字體顯示當(dāng)前的系統(tǒng)時(shí)間。
import java.awt.*; import java.applet.Applet; import java.util.*; import java.awt.Graphics; public class clock extends Applet implements Runnable //繼承Applet類并實(shí)現(xiàn)Runnable接口 { Thread clockThread=null; //創(chuàng)建一個(gè)空線程 Calendar now; private String s1; private int size; int r1,g1,b1; public void init() //初始化方法 { size=Integer.parseInt(getParameter("size"));//獲得字體大小 } public void start() { if(clockThread==null) { clockThread=new Thread(this,"Clock2"); //創(chuàng)建線程對(duì)象clockThread clockThread.start(); //開始執(zhí)行線程 } } public void run() //實(shí)現(xiàn)Runnable接口的run()方法 { Thread myThread=Thread.currentThread();//創(chuàng)建線程對(duì)象myThread while(clockThread==myThread) { repaint(); //通過repaint方法調(diào)用paint方法 try { Thread.sleep(1000); //休眠1秒 } catch (InterruptedException e){} } } public void paint(Graphics g) { r1=(int)(Math.random()*255); //通過調(diào)用Math類的random產(chǎn)生隨機(jī)數(shù) g1=(int)(Math.random()*255); //再通過隨機(jī)數(shù)分別設(shè)置三原色,紅綠藍(lán) b1=(int)(Math.random()*255); Color c=new Color(r1,g1,b1); //創(chuàng)建一個(gè)顏色對(duì)象 g.setColor(c); //設(shè)置顏色 now=Calendar.getInstance(); //獲得系統(tǒng)當(dāng)前時(shí)間 s1=now.get(now.HOUR)+"時(shí)" +now.get(now.MINUTE)+"分" +now.get(now.SECOND)+"秒"; Font f=new Font("",1,size); //設(shè)置字體 g.setFont(f); g.drawString(s1,10,50); //顯示指定大小顏色的字符串 } public void stop() //調(diào)用stop方法,停止線程 { clockThread=null; } } <pre class="html" name="code"><html> <Applet code="clock.class" width=300 height=100> <param name=s1 value=s1> <param name=size value=30> </Applet> </html></pre><br> <pre></pre> <p> </p> <pre></pre> <div style="padding-top:20px"> <p style="font-size:12px;">利用線程實(shí)現(xiàn)動(dòng)態(tài)顯示系統(tǒng)時(shí)間</p> </div>
這就是如何利用線程實(shí)現(xiàn)動(dòng)態(tài)顯示系統(tǒng)時(shí)間的方法,希望對(duì)大家的學(xué)習(xí)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選