欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java实现时间动态显示方法汇总

程序员文章站 2024-02-28 09:33:52
本文所述实例可以实现java在界面上动态的显示时间。具体实现方法汇总如下: 1.方法一 用timertask: 利用java.util.timer和java.util....

本文所述实例可以实现java在界面上动态的显示时间。具体实现方法汇总如下:

1.方法一 用timertask:

利用java.util.timer和java.util.timertask来做动态更新,毕竟每次更新可以看作是计时1秒发生一次。
代码如下:

import java.awt.dimension;
import java.text.simpledateformat;
import java.util.calendar;
import java.util.date;
import java.util.timer;
import java.util.timertask;
import javax.swing.jframe;
import javax.swing.jlabel;
import javax.swing.jpanel;
/**
 * this class is a simple jframe implementation to explain how to
 * display time dynamically on the jswing-based interface.
 * @author edison
 *
 */
public class timeframe extends jframe
{
 /*
 * variables 
 */
 private jpanel timepanel;
 private jlabel timelabel;
 private jlabel displayarea;
 private string default_time_format = "hh:mm:ss";
 private string time;
 private int one_second = 1000;
 
 public timeframe()
 {
 timepanel = new jpanel();
 timelabel = new jlabel("currenttime: ");
 displayarea = new jlabel();
 
 configtimearea();
 
 timepanel.add(timelabel);
 timepanel.add(displayarea);
 this.add(timepanel);
 this.setdefaultcloseoperation(exit_on_close);
 this.setsize(new dimension(200,70));
 this.setlocationrelativeto(null);
 }
 
 /**
 * this method creates a timer task to update the time per second
 */
 private void configtimearea() {
 timer tmr = new timer();
 tmr.scheduleatfixedrate(new jlabeltimertask(),new date(), one_second);
 }
 
 /**
 * timer task to update the time display area
 *
 */
 protected class jlabeltimertask extends timertask{
 simpledateformat dateformatter = new simpledateformat(default_time_format);
 @override
 public void run() {
  time = dateformatter.format(calendar.getinstance().gettime());
  displayarea.settext(time);
 }
 }
 
 public static void main(string arg[])
 {
 timeframe timeframe=new timeframe();
 timeframe.setvisible(true); 
 } 
}
 


继承timertask来创建一个自定义的task,获取当前时间,更新displayarea.
然后创建一个timer的实例,每1秒执行一次timertask。由于用schedule可能会有时间误差产生,所以直接调用精度更高的scheduleatfixedrate的。
 
2. 方法二:利用线程:

这个就比较简单了。具体代码如下:

import java.awt.dimension;
import java.text.simpledateformat;
import java.util.calendar;
import javax.swing.jframe;
import javax.swing.jlabel;
import javax.swing.jpanel;
/**
 * this class is a simple jframe implementation to explain how to
 * display time dynamically on the jswing-based interface.
 * @author edison
 *
 */
public class dtimeframe2 extends jframe implements runnable{
 private jframe frame;
 private jpanel timepanel;
 private jlabel timelabel;
 private jlabel displayarea;
 private string default_time_format = "hh:mm:ss";
 private int one_second = 1000;
 
 public dtimeframe2()
 {
 timepanel = new jpanel();
 timelabel = new jlabel("currenttime: ");
 displayarea = new jlabel();
 
 timepanel.add(timelabel);
 timepanel.add(displayarea);
 this.add(timepanel);
 this.setdefaultcloseoperation(exit_on_close);
 this.setsize(new dimension(200,70));
 this.setlocationrelativeto(null);
 }
 public void run()
 {
 while(true)
 {
  simpledateformat dateformatter = new simpledateformat(default_time_format);
  displayarea.settext(dateformatter.format(
     calendar.getinstance().gettime()));
  try
  {
  thread.sleep(one_second); 
  }
  catch(exception e)
  {
  displayarea.settext("error!!!");
  }
 } 
 } 
 
 public static void main(string arg[])
 {
 dtimeframe2 df2=new dtimeframe2();
 df2.setvisible(true);
 
 thread thread1=new thread(df2);
 thread1.start(); 
 } 
}

比较:

个人倾向于方法一,因为timer是可以被多个timertask共用,而产生一个线程,会增加多线程的维护复杂度。

注意如下代码:

jframe.setdefaultcloseoperation(); // 给关闭按钮增加特定行为
jframe.setlocationrelativeto(null); // 让frame一出来就在屏幕中间,而不是左上方。

将上面方法一稍微一修改,就可以显示多国时间。代码如下:

import java.awt.borderlayout;
import java.awt.event.actionevent;
import java.awt.event.actionlistener;
import java.text.simpledateformat;
import java.util.calendar;
import java.util.date;
import java.util.locale;
import java.util.timezone;
import java.util.timer;
import java.util.timertask;
import javax.swing.defaultcomboboxmodel;
import javax.swing.jcombobox;
import javax.swing.jframe;
import javax.swing.jlabel;
import javax.swing.jpanel;
/**
 * a simple world clock
 * @author edison
 *
 */
public class worldtimeframe extends jframe
{
 /**
 * 
 */
 private static final long serialversionuid = 4782486524987801209l;
 
 private string time;
 private jpanel timepanel;
 private timezone timezone;
 private jcombobox zonebox;
 private jlabel displayarea;
 
 private int one_second = 1000;
 private string default_format = "eee d mmm, hh:mm:ss";
 
 public worldtimeframe()
 {
 zonebox = new jcombobox();
 timepanel = new jpanel();
 displayarea = new jlabel();
 timezone = timezone.getdefault();
 
 zonebox.setmodel(new defaultcomboboxmodel(timezone.getavailableids()));
 
 zonebox.addactionlistener(new actionlistener(){
  @override
  public void actionperformed(actionevent e) {
  updatetimezone(timezone.gettimezone((string) zonebox.getselecteditem()));
  }
  
 });
 
 configtimearea();
 
 timepanel.add(displayarea);
 this.setlayout(new borderlayout());
 this.add(zonebox, borderlayout.north);
 this.add(timepanel, borderlayout.center);
 this.setlocationrelativeto(null);
 this.setdefaultcloseoperation(exit_on_close);
 this.setvisible(true);
 pack();
 }
 
 /**
 * this method creates a timer task to update the time per second
 */
 private void configtimearea() {
 timer tmr = new timer();
 tmr.scheduleatfixedrate(new jlabeltimertask(),new date(), one_second);
 }
 
 /**
 * timer task to update the time display area
 *
 */
 public class jlabeltimertask extends timertask{
 simpledateformat dateformatter = new simpledateformat(default_format, locale.english);
 @override
 public void run() {
  dateformatter.settimezone(timezone);
  time = dateformatter.format(calendar.getinstance().gettime());
  displayarea.settext(time);
 }
 }
 
 /**
 * update the timezone
 * @param newzone
 */
 public void updatetimezone(timezone newzone)
 {
 this.timezone = newzone;
 }
 
 public static void main(string arg[])
 {
 new worldtimeframe();
 } 
}

本来需要在updatetimezone(timezone newzone)中,更新displayarea的。但是考虑到timertask执行的时间太短,才1秒钟,以肉眼观察,基本上是和立刻更新没区别。如果timertask执行时间长的话,这里就要立刻重新用心的时间更新一下displayarea。

补充:

①. pack() 用来自动计算屏幕大小;
②. timezone.getavailableids() 用来获取所有的timezone。