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

这篇文章主要介绍了Java实现时间动态显示方法汇总,很实用的功能,需要的朋友可以参考下本文所述实例可以实现Java在界面上动态的显示时间。具体实现方法汇总如下:1.方法一用TimerTask:

大家好,又见面了,我是全栈君,今天给大家准备了Idea注册码。

这篇文章主要介绍了Java实现时间动态显示方法汇总,很实用的功能,需要的朋友可以参考下

本文所述实例可以实现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); 
 } 
}/* 何问起 hovertree.com */

继承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(); 
 } 
}
/* hwq2.com */

比较:

个人倾向于方法一,因为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();
 } 
}/* 何问起 hovertree.com */

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

补充:

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

推荐:http://www.cnblogs.com/roucheng/p/3504465.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/120324.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 两个元素的矩阵乘除法「建议收藏」

    矩阵的乘除法: 1 矩阵相乘,两个矩阵只有当左边的矩阵的列数等于右边矩阵的行数时,两个矩阵才可以进行矩阵的乘法运算 主要方法就是:用左边矩阵的第一行,逐个乘以右边矩阵的列,第一行与第一列各个元素的乘积相加,第一行与第二列的各个元素的乘积相加。。。。第二行也是,逐个乘以右边矩阵的列。。。。第三行。。。。。。。最后得出结果不明白的可以继续往下看   2…

    2022年4月4日
    62
  • vue 路由嵌套_vuejs直接打开第三级路由

    vue 路由嵌套_vuejs直接打开第三级路由嵌套路由有时候在路由中,主要的部分是相同的,但是下面可能是不同的。比如访问首页,里面有新闻类的/home/news,还有信息类的/home/message。这时候就需要使用到嵌套路由。项目结构如下:

    2022年8月7日
    7
  • 对比自监督学习综述 – A Survey of Contrastive Self-Supervised Learning

    对比自监督学习综述 – A Survey of Contrastive Self-Supervised Learning本文介绍了最近流行的对比自监督学习。

    2022年9月14日
    0
  • 收藏几款好用的网页下载工具(网页下载器)「建议收藏」

    收藏几款好用的网页下载工具(网页下载器)「建议收藏」收藏几款好用的网页下载工具(网页下载器)引言webzipTeleportUltraTeleportUltra小飞兔下载MihovPictureDownloaderWinHTTrackHTTrack仿站小工具引言有的人利用网页下载工具下载网站到本地进行慢慢的欣赏,有的人利用下载工具创建垃圾站。不管你是出于什么样的目的,下面这些工具软件你可以会需要。webzip一款国外的网页下载器,把一个网站下载并压缩到一个单独的ZIP文件中,可以帮您将某个站台全部或部份之资料以ZIP格式压缩起来,可供你日后

    2022年6月11日
    1.0K
  • Windows net start mysql 启动MySQL服务报错 发生系统错误 5 解决方法

    Windows net start mysql 启动MySQL服务报错 发生系统错误 5 解决方法netstartmysql启动MySQL服务报错发生系统错误5解决方法

    2022年7月14日
    31
  • densenet详解_dense参数

    densenet详解_dense参数DenseNet于论文《》中提出,是CVPR2017的oral。论文提出DenseNet并与ResNet和Inception做对较。为提升网络的效果,一般操作是增加网络的深度和宽度,但论文作者另辟蹊径,聚焦于feature的极致利用以获得更佳效果和更少参数。对于梯度消失问题,ResNet等网络使用跳层连接结构加以解决。作者延续该思路,提出DenseBlock,在保证网络层间最大程度的信息传输的同时,直接将所有层连接起来。……………………

    2022年9月29日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号