Java编程——数字时钟

 1 //ClockDemo.java
 2 
 3 /*
 4 * To change this license header, choose License Headers in Project Properties.
 5 * To change this template file, choose Tools | Templates
 6 * and open the template in the editor.
 7 */
 8 package newpackage;
 9 import java.awt.*;
10 import java.util.*;
11 import javax.swing.*;
12 
13 //数字时钟
14 public class ClockDemo extends JFrame implements Runnable{
15 Thread clock;    
16 
17 public ClockDemo(){
18 super("数字时钟");    //调用父类构造函数    
19 setFont(new Font("Times New Roman",Font.BOLD,60));    //设置时钟的显示字体
20 start(); //开始进程
21 setSize(280,100); //设置窗口尺寸
22 setVisible(true); //窗口可视
23 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序
24 }
25 
26 public void start(){ //开始进程
27 if (clock==null){ //如果进程为空值
28 clock=new Thread(this); //实例化进程
29 clock.start(); //开始进程
30 }
31 }
32 
33 public void run(){ //运行进程
34 while (clock!=null){ 
35 repaint(); //调用paint方法重绘界面
36 try{
37 Thread.sleep(1000); //线程暂停一秒(1000毫秒)
38 }
39 catch (InterruptedException ex){
40 ex.printStackTrace(); //输出出错信息
41 }
42 }    
43 }
44 
45 public void stop(){ //停止进程
46 clock=null;
47 }
48 
49 public void paint(Graphics g){ //重载组件的paint方法
50 Graphics2D g2=(Graphics2D)g; //得到Graphics2D对象
51 Calendar now=new GregorianCalendar(); //实例化日历对象
52 String timeInfo=""; //输出信息
53 int hour=now.get(Calendar.HOUR_OF_DAY); //得到小时数
54 int minute=now.get(Calendar.MINUTE); //得到分数
55 int second=now.get(Calendar.SECOND); //得到秒数
56 
57 if (hour<=9) 
58 timeInfo+="0"+hour+":"; //格式化输出
59 else 
60 timeInfo+=hour+":";
61 if (minute<=9)
62 timeInfo+="0"+minute+":";
63 else
64 timeInfo+=minute+":";
65 if (second<=9)
66 timeInfo+="0"+second;
67 else
68 timeInfo+=second;
69 
70 g.setColor(Color.white); //设置当前颜色为白色
71 Dimension dim=getSize(); //得到窗口尺寸
72 g.fillRect(0,0,dim.width,dim.height); //填充背景色为白色
73 g.setColor(Color.orange); //设置当前颜色为橙色
74 g.drawString(timeInfo,20,80); //显示时间字符串
75 }
76 
77 public static void main(String[] args){
78 new ClockDemo();
79 }
80 }
源代码:

 

 

posted on 2017-10-24 22:00  小星_log  阅读(1528)  评论(0编辑  收藏  举报