北京北大青鳥學(xué)術(shù)部:如何使用Java實(shí)現(xiàn)數(shù)字時鐘

北京北大青鳥通州校區(qū)提供:

import java.awt.*;
import javax.swing.*;
import java.util.Calendar;

public class AccpClock extends JFrame implements Runnable {

 Thread clock;
 public AccpClock() {
  super("通州北大青鳥,java多線程數(shù)字時鐘");
  //設(shè)置時鐘標(biāo)題
  setTitle("ACCP數(shù)字時鐘");
  //設(shè)置時鐘字體類型及大小
  this.setFont(new Font("Times New Roman", Font.BOLD, 60)); // 設(shè)置字體大小
  //自定義go方法,用于以后開啟線程
  this.go();
  //設(shè)置時鐘界面大小
  setBounds(400, 300, 280, 100);
  //設(shè)置時鐘為可見
  this.setVisible(true);
 }

 public void go() {
  stop();
  if (clock == null) {
   // 線程執(zhí)行的主題作為Thread類構(gòu)造方法的參數(shù)。
   clock = new Thread(this);
   // 開啟線程,實(shí)現(xiàn)run方法
   clock.start();
  }
 }

 public void run() {
  // 死循環(huán),讓時鐘一直走
  while (true)
  {
   //repain()方法是來控制Graphics類的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 = "";
  //獲取日歷對象
  Calendar cale = Calendar.getInstance();
  //獲取當(dāng)前小時
  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)前時間
  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)行時鐘
 public static void main(String[] args) {
  AccpClock td = new AccpClock();
  //點(diǎn)擊可見窗口右上角的按鈕關(guān)閉
  td.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
}

北大青鳥網(wǎng)上報(bào)名
北大青鳥招生簡章