北京北大青鳥(niǎo)通州校區(qū)提供:
import java.awt.*;
import javax.swing.*;
import java.util.Calendar;
public class AccpClock extends JFrame implements Runnable {
Thread clock;
public AccpClock() {
super("通州北大青鳥(niǎo),java多線(xiàn)程數(shù)字時(shí)鐘");
//設(shè)置時(shí)鐘標(biāo)題
setTitle("ACCP數(shù)字時(shí)鐘");
//設(shè)置時(shí)鐘字體類(lèi)型及大小
this.setFont(new Font("Times New Roman", Font.BOLD, 60)); // 設(shè)置字體大小
//自定義go方法,用于以后開(kāi)啟線(xiàn)程
this.go();
//設(shè)置時(shí)鐘界面大小
setBounds(400, 300, 280, 100);
//設(shè)置時(shí)鐘為可見(jiàn)
this.setVisible(true);
}
public void go() {
stop();
if (clock == null) {
// 線(xiàn)程執(zhí)行的主題作為T(mén)hread類(lèi)構(gòu)造方法的參數(shù)。
clock = new Thread(this);
// 開(kāi)啟線(xiàn)程,實(shí)現(xiàn)run方法
clock.start();
}
}
public void run() {
// 死循環(huán),讓時(shí)鐘一直走
while (true)
{
//repain()方法是來(lái)控制Graphics類(lèi)的paint()方法的,repain()方法執(zhí)行一次,即讓paint()方法執(zhí)行一次
repaint();
try {
//參數(shù)是毫秒,1秒即1000毫秒
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
public void stop() {
clock = null;
}
public void paint(Graphics g) {
String s = "";
//獲取日歷對(duì)象
Calendar cale = Calendar.getInstance();
//獲取當(dāng)前小時(shí)
int hour = cale.get(Calendar.HOUR_OF_DAY) ;
//獲取當(dāng)前分鐘
int minute = cale.get(Calendar.MINUTE);
//獲取當(dāng)前秒數(shù)
int second = cale.get(Calendar.SECOND);
//格式化輸出當(dāng)前時(shí)間
String now = String.format("%1$02d:%2$02d:%3$02d", hour,minute,second);
//設(shè)置背景顏色為綠色
g.setColor(Color.green);
Dimension dim = getSize();
g.fillRect(0, 0, dim.width, dim.height);
g.setColor(Color.red);
g.drawString(now, 20, 80);
}
//Main方法,運(yùn)行時(shí)鐘
public static void main(String[] args) {
AccpClock td = new AccpClock();
//點(diǎn)擊可見(jiàn)窗口右上角的按鈕關(guān)閉
td.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}