使JLabel动态的显示系统时间

类的使用说明: 此类内部用的是Java.swing.Timer类实现的系统时间更新功能 更新需要写到一个JLabel 上,我本来是用他做为一个程序状态栏使用的 java 中就没用状态栏所以用一个jLabel模拟了把它加的一个面板的底部(你知道的用流布局 是右下角位值 正如你往你计算机右下角看到的那样)不管你把它加到什么上了 反正在你实列化JLabel后 把其引用传给它就行了时间的更新交给我写的这个类就o了如:javax.swing.JLabel aTimeLabel=new JLabel("此字符串将被替换"); new SystTimeUpdateTimer(JLabel jLabel);就行了 本来是想写个静太方法 但是没时间了 留给使用者或是以后有时间来改 此类不需要引用也能工作 所以做为工具类应更有意义 里面有硬编码成份:字符串,时间间隔 还有显示时间的格式都可以变动根据需要 把这些都写成可变或是可配置的,需要些时间不过不会太多加几个方法就行了参数当然就是字符串和时间间隔,还有显示日期格式的方法多写几个。我没有考虑多线程问题!!!

     还有注意Swing 计时器的局限性:他可以共享以有的线程,与GUI 相关的任务都在事件分发线程里面执行,所以如果操作比较长的话选择常规的计时器不然会影响界面的显示(用util包中的哪个)或者配合SwingWorker类!!!

import javax.swing.Timer;
import javax.swing.JLabel;
import java.util.Calendar;
import java.util.TimeZone;
import java.text.DateFormat;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class SystTimeUpdateTimer implements ActionListener {
       public      final         int ONE_SECOND=1000;      //1秒钟更新一次
private     JLabel        timeLabel=null;           //在此label上显示时间由外部传入
       private     Calendar      calendar=null;     //获取当前时间的日历类
       private     DateFormat dateFormat=null;       //时间格式类 用来格式化时间用
       private     Timer         timeTimer=null;        //计时器
       private     TimeZone currentTimeZone;         //*当前的时区 只所以
       //用它是因为返回的时间可能跟时区有关而跟你机器上的相差几小时我就遇到过*/
   
       public SystTimeUpdateTimer(JLabel jLabel) {
     // TODO Auto-generated constructor stub
     this.timeLabel=jLabel;    
     this.currentTimeZone=TimeZone.getDefault();//此方法返回本地时区 程序运行的地方
     this.dateFormat=DateFormat.getDateTimeInstance(2,2,java.util.Locale.getDefault());

     //this.dateFormat=          //上面的是简写下面的是带汉字的如 2007年4月 3点4分5秒 自己试试
     //DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG,java.util.Locale.getDefault());//此为完整的时间格式
     this.timeTimer=new Timer(this.ONE_SECOND,this);
     this.timeTimer.setRepeats(true);
     this.timeTimer.start();
}
public void stopTimer()
{
     this.timeTimer.stop();
}
public void reStartTimer()
{
     this.timeTimer.restart();
}

  

//下面就是计时器每隔一定时间做的事
public void actionPerformed(ActionEvent arg0) {
     // TODO Auto-generated method stub
     this.calendar=Calendar.getInstance(this.currentTimeZone);
     this.timeLabel.setText("当前系统时间:"+this.dateFormat.format(this.calendar.getTime()));   
  
     //下面的也可以 更精确些 不过把计时器的时间间隔弄小些不然刷新跟不上豪秒就不显示了
     //java.sql.Timestamp timeStamp=new     java.sql.Timestamp(System.currentTimeMillis());  
        //this.timeLabel.setText(timeStamp.toString());
}
}

  

 

 

 

原文http://hi.baidu.com/yiqing95/blog/item/454c5ca7ba08e094d14358c0.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值