您的位置:首页 > 编程语言 > Java开发

java 制作电子时钟

2010-08-07 22:55 351 查看
一个小巧的电子时钟Java源代码,代码简单易懂,初学Java者可以看看玩玩。。

源代码:

import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class Clock extends JPanel implements ActionListener{

public Clock(){
//创建一个监听事件
ActionListener drawClock = new ActionListener(){
public void actionPerformed(ActionEvent evt){

repaint();
}
};
//创建一个时间计数器
new Timer(1000,drawClock).start();
}

public void actionPerformed(ActionEvent e){
}
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.black);
Calendar now= new GregorianCalendar();
int nowh= now.get(Calendar.HOUR_OF_DAY);
int nowm= now.get(Calendar.MINUTE);
int nows= now.get(Calendar.SECOND);
String st = null;

//这部分是显示在时间前面的字。。可以自由改动
if(nowh>23||nowh<=6){st="夜深啦,早点休息!现在是:";}
if(nowh>6&&nowh<=12){st="上午好!现在是:";}
if(nowh>12&&nowh<=18){st="下午好!现在是:";}
if(nowh>18&&nowh<=23){st="晚上好!现在是:";}
if(nowh<10) st+="0"+nowh;else st+=""+nowh;
if(nowm<10) st+=":0"+nowm;else st+=":"+nowm;
if(nows<10) st+=":0"+nows;else st+=":"+nows;
//在窗体上显示时间
g.setColor(Color.red);//窗体上的时间下背景色
g.fillRect(5,5,100,28);
g.setFont(new Font("华文彩云",Font.BOLD,15));//设置时间字体的字体类型和大小
g.setColor(Color.blue);//时间的字体颜色
g.drawString(st,15,15);
this.updateUI();
}

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