java 制作电子时钟

一个小巧的电子时钟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();
   }
  
}

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值