这篇文章主要介绍了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

Java实现时间动态显示方法汇总的更多相关文章

  1. Python实用日期时间处理方法汇总

    这篇文章主要介绍了Python实用日期时间处理方法汇总,本文讲解了获取当前datetime.获取当天date.获取明天/前N天.获取当天开始和结束时间(00:00:00 23:59:59).获取两个d ...

  2. java比较时间的方法

    一.通过compareTo Date date = new Date(1576118709574L); Date date1 = new Date(1576118709574L); Date date ...

  3. java中文乱码解决方法汇总

    public static void main(String[] argv){ try {                 System.out.println(“中文”);//1           ...

  4. java中获取日期和时间的方法总结

    1.获取当前时间,和某个时间进行比较.此时主要拿long型的时间值. 方法如下:  要使用 java.util.Date .获取当前时间的代码如下 Date date = new Date(); da ...

  5. OpenCV3 Java 机器学习使用方法汇总

    原文链接:OpenCV3 Java 机器学习使用方法汇总  前言 按道理来说,C++版本的OpenCV训练的版本XML文件,在java中可以无缝使用.但要注意OpenCV本身的版本问题.从2.4 到3 ...

  6. Java向mysql中插入时间的方法

    ava向MySQL插入当前时间的四种方式和java时间日期格式化的几种方法(案例说明);部分资料参考网络资源  java向MySQL插入当前时间的四种方式 第一种:将java.util.Date类型的 ...

  7. Java快速入门-03-小知识汇总篇(全)

    Java快速入门-03-小知识汇总篇(全) 前两篇介绍了JAVA入门的一系小知识,本篇介绍一些比较偏的,说不定什么时候会用到,有用记得 Mark 一下 快键键 常用快捷键(熟记) 快捷键 快捷键作用 ...

  8. 最常见的Java面试题及答案汇总(三)

    上一篇:最常见的Java面试题及答案汇总(二) 多线程 35. 并行和并发有什么区别? 并行是指两个或者多个事件在同一时刻发生:而并发是指两个或多个事件在同一时间间隔发生. 并行是在不同实体上的多个事 ...

  9. java 多线程40个问题汇总(转)

    java 多线程40个问题汇总,自己也记录一份,如有侵权,联系删除 ref from :http://www.cnblogs.com/xrq730/p/5060921.html 1.多线程作用 - 利 ...

随机推荐

  1. jQuery 2.0.3 源码分析 Deferred(最细的实现剖析,带图)

    Deferred的概念请看第一篇 http://www.cnblogs.com/aaronjs/p/3348569.html ******************构建Deferred对象时候的流程图* ...

  2. SQL Server 数据库设计规范

    数据库设计规范 1.简介 数据库设计是指对一个给定的应用环境,构造最优的数据库模式,建立数据库及其他应用系统,使之能有效地存储数据,满足各种用户的需求.数据库设计过程中命名规范很是重要,命名规范合理的 ...

  3. 《Entity Framework 6 Recipes》中文翻译系列 (9) -----第二章 实体数据建模基础之继承关系映射TPH

    翻译的初衷以及为什么选择<Entity Framework 6 Recipes>来学习,请看本系列开篇 2-10 Table per Hierarchy Inheritance 建模 问题 ...

  4. struts2+spring+hibernate 实现分页

    在这里要感谢下这位博友发表的博文 http://www.blogjava.net/rongxh7/archive/2008/11/29/243456.html 通过对他代码的阅读,从而自己实现了网页分 ...

  5. 设有一数据库,包括四个表:学生表(Student)、课程表(Course)、成绩表(Score)以及教师信息表(Teacher)。

    一.            设有一数据库,包括四个表:学生表(Student).课程表(Course).成绩表(Score)以及教师信息表(Teacher).四个表的结构分别如表1-1的表(一)~表( ...

  6. 蓝桥杯 十六进制转八进制(超大测试数据,java实现)

    问题描述 给定n个十六进制正整数,输出它们对应的八进制数.输入格式 输入的第一行为一个正整数n (1<=n<=10). 接下来n行,每行一个由0~9.大写字母A~F组成的字符串,表示要转换 ...

  7. Powershell 切换IE代理

    买了一个穿越防火墙的代理,在 Windows 下每次手动设置代理都好麻烦,最后不断尝试 Powershell 来设置,最后也终于成功了.   其实利用 Powershell 来设置 IE 的代理,就是 ...

  8. 【转】C#调用Windows图片和传真查看器打开图片

    //建立新的系统进程 System.Diagnostics.Process process = new System.Diagnostics.Process(); //设置文件名,此处为图片的真实路径 ...

  9. 前端学PHP之变量范围

    × 目录 [1]范围跨度 [2]函数范围 [3]global[4]预定义变量[5]超全局变量 前面的话 变量范围即它定义的上下文背景(也就是它的生效范围).在javascript中,并没有变量范围这一 ...

  10. ASP.NET Core中的依赖注入(5):ServicePrvider实现揭秘【补充漏掉的细节】

    到目前为止,我们定义的ServiceProvider已经实现了基本的服务提供和回收功能,但是依然漏掉了一些必需的细节特性.这些特性包括如何针对IServiceProvider接口提供一个Service ...