您的位置:首页 > 其它

利用多线程实现电子时钟

2012-09-03 18:52 375 查看
 

import java.util.Calendar;

import java.util.GregorianCalendar;

import javax.swing.JFrame;

import javax.swing.JLabel;

public class Clock {

 /**

  * @param args

  */

 public static void main(String[] args) {

  //布局电子时钟界面

  JFrame jf=new JFrame("Clock");

  JLabel jl=new JLabel("Clock");

  jl.setHorizontalAlignment(JLabel.CENTER);

  jf.add(jl,"Center");

  jf.setSize(200,150);

  jf.setLocation(400,200);

  jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  jf.setVisible(true);

  

//多线程开始

  Thread t = new MyThread(jl);

  t.start();

 }

}

 class MyThread extends Thread{

  private JLabel clock;

  public MyThread(JLabel clock){

   this.clock = clock;

  }

  public void run(){

   while(true){

    clock.setText(this.getTime());

    try {

     //休眠一秒钟

     Thread.sleep(1000);

    } catch (InterruptedException e) {

     // TODO Auto-generated catch block

     e.printStackTrace();

    }

   }

  }

  private String getTime() {

   

   Calendar c = new GregorianCalendar();

   //获取日期

   String time = c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH)+1) + "-" +c.get(Calendar.DATE) + "   ";

   //获取时刻

   int hour = c.get(Calendar.HOUR_OF_DAY);

   int minute = c.get(Calendar.MINUTE);

   int second = c.get(Calendar.SECOND);

   //当时间不足10的时候,在个位数前加一个0,使时间整齐

   String ph = hour < 10 ? "0" : "";

   String pm = minute < 10 ? "0" : "";

   String ps = second < 10 ? "0" : "";

   

   time += ph + hour + ":" + pm + minute + ":" + ps + second;

   return time;

  }

 }

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息