日期:2014-05-20 浏览次数:20772 次
import java.awt.Frame; import java.awt.Label; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; public class Test1 { public static void main(String[] args) { Clock clock = new Clock(); Frame f = new Frame(); f.setSize(300, 300); f.add(clock); clock.start(); //自动计时开始 f.setVisible(true); try { Thread.sleep(10000); clock.close(); //10秒后计时停止 } catch (InterruptedException e) { e.printStackTrace(); } } } class Clock extends Label { Clocker cl; public Clock() { cl = new Clocker(); } public void start() { cl.start(); } public void close() { cl.setF(); } class Clocker extends Thread { Date time = null; boolean f = true; public void run() { GregorianCalendar gc = new GregorianCalendar(Locale.CHINA); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA); while(f) { Clock.this.setText(sf.format(gc.getTime())); try { Thread.sleep(1000); gc.set(Calendar.SECOND,gc.get(Calendar.SECOND)+1); } catch (InterruptedException e) { e.printStackTrace(); } } } public void setF() { f = false; } } }