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)
上一篇 2021年12月27日 下午2:00
下一篇 2021年12月27日 下午2:00


相关推荐

  • 量化进阶——量化交易模型的“钝化”与“圣杯”[通俗易懂]

    量化进阶——量化交易模型的“钝化”与“圣杯”[通俗易懂]阅读原文:http://club.jr.jd.com/quant/topic/1326857京东金融官方资讯QQ群:417082141有什么想咨询的都可以来询问我们哦钝化的烦恼常有人提到量化交易模型的“钝化”问题,通俗的说,也就是一个模型从赚大钱变为不赚钱,甚至亏损的一个过程。甚至在海洋部落那样高手云集的社会中,不少高人眼里,钝化是每个量化交易模型都会很快发生的事,赚钱机

    2022年6月26日
    39
  • OleDbDataAdapter 具体使用案例

    OleDbDataAdapter 具体使用案例usingSystem usingSystem Collections Generic usingSystem ComponentMod usingSystem Data usingSystem Data OleDb usingSystem Data SqlClient usingSystem Drawing usingSystem Linq

    2026年3月17日
    1
  • CAP 理论

    CAP 理论CAP 是分布式系统中典型的基础理论 它主要表达 C A P 不存在三全其美的的选择 CAP 是分布式系统中三个特性的英文首字母组合 分别对应 一致性 Consistency 可用性 Availability 分区容错性 Partitiontol 在这个理论中 最多只能同时做到其中的两个特性 要么满足 CA 要么满足 CP 要么满足 AP 同时满足 CAP 是不可能的 一致性 C 在分布式系统完成某写操作后再进行任何读操作 都应该获取到该写操作写入的那个最新的值

    2026年3月16日
    2
  • 微信公众号网页开发,登录授权和微信支付

    微信公众号网页开发,登录授权和微信支付微信公众号的网页开发基本和H5移动端开发一致,主要是涉及到网页授权获取用户信息和使用js-sdk获取微信原生能力支持。开发前准备申请一个测试号:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login用自己微信扫码登录,然后扫码关注当前测试号,这里注意js接口安全域名和网页授权回调域名,需要配置为当前项目地址。使用测试号时用ip即可,但是线上必须是域名。网页授权类似把系统自己的登录体系移除,通过微信授权方式获取微信用户信息。

    2022年6月5日
    134
  • ubuntu 开机遇到grub解决方法超详细_linux开机grub>命令修复方法

    ubuntu 开机遇到grub解决方法超详细_linux开机grub>命令修复方法grub是引导程序,它可以引导多操作系统。开机出现grub,多半是grub文件损坏了。下面介绍修复方法查找grub所在的分区,ubuntu没有另外建分区是在/boot/grub文件夹#第一步:输入ls出现(hd0,msods1),(hd0,msdos5),(hd0,msods7)#不同的电脑不一样,这是我电脑中的磁盘分区,和系统中的表示方法不一样,#linux…

    2025年8月12日
    6
  • Java8中Date转换LocalDate、LocalDate转换Date、Date转换LocalDateTime

    Java8中Date转换LocalDate、LocalDate转换Date、Date转换LocalDateTime@TestpublicvoidtimeTest(){Datedate=newDate();//date转换为localDateTimeLocalDateTimelocalDateTime=LocalDateTime.ofInstant(date.toInstant(),ZoneId.systemDefault());System.out.println(“localDateTime=”+l…

    2026年4月13日
    4

发表回复

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

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