如何使用Applet来显示时钟?
解决方法
下面的示例演示如何显示使用String类的valueOf ()方法。以及使用Calendar类来获得秒,分钟和小时。
import java.awt.*; import java.applet.*; import java.applet.*; import java.awt.*; import java.util.*; public class ClockApplet extends Applet implements Runnable{ Thread t,t1; public void start(){ t = new Thread(this); t.start(); } public void run(){ t1 = Thread.currentThread(); while(t1 == t){ repaint(); try{ t1.sleep(1000); } catch(InterruptedException e){} } } public void paint(Graphics g){ Calendar cal = new GregorianCalendar(); String hour = String.valueOf(cal.get(Calendar.HOUR)); String minute = String.valueOf(cal.get(Calendar.MINUTE)); String second = String.valueOf(cal.get(Calendar.SECOND)); g.drawString(hour + ":" + minute + ":" + second, 20, 30); } }
结果
上面的代码示例将产生在一个支持java的web浏览器,结果如下。
View in Browser.