为什么 Java 中有两个 Timer 类(一个在 javax.swing 下,一个在 java.util 下)? [英] Why are there two Timer classes in Java(one under javax.swing, one under java.util )?
问题描述
我真的很困惑.Java 有两个 Timer 类,一个在 swing 下,还有一个在 util 下......为什么就是它?如果我只想每 Y 秒运行一次 X,我应该使用哪一个?这是否意味着如果我正在构建一个 GUI,我必须使用 Swing 版本作为计时器?
I am really confused about this . Java has two Timer classes, one under swing , and one under util ... why is that? Which one should I use if I want to simply run X every Y seconds? Does this mean if I'm building a GUI I have to use the swing version for a timer?
谢谢!
推荐答案
javax.swing.Timer 和 java.util.Timer 的区别如下:
Here is the difference between javax.swing.Timer and java.util.Timer:
javax.swing.Timer
- 适用于更简单的情况,使用少量计时器(比如少于一打)
- 在事件调度线程上运行 ActionListener 对象
- 可以直接更新GUI,无需使用EventQueue.invokeLater
- 如果任务完全在事件分派线程中运行(也就是说,如果它不产生工作线程),那么只有当任务不需要很长时间(比如低于 300 毫秒)时,GUI 才会保持响应 莉>
- 比 javax.swing.Timer 更具可扩展性,并具有额外的调度功能
- 在私有线程上运行 TimerTask 对象
- 需要使用 EventQueue.invokeLater 来更新 GUI
- 在延迟之后执行一次任务.例如,工具提示管理器使用 Swing 计时器来确定何时显示工具提示以及何时隐藏它.
- 重复执行一项任务.例如,您可以执行动画或更新显示目标进度的组件.
java.util.Timer
您可以通过两种方式使用 Swing 计时器:
You can use Swing timers in two ways:
这里是上述信息的来源 http://www.javapractices.com/topic/TopicAction.do?Id=160 和 http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html
Here is the sources for above information http://www.javapractices.com/topic/TopicAction.do?Id=160 and http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html
如果我只想每 Y 秒运行一次 X,我应该使用哪个?
Which one should I use if I want to simply run X every Y seconds?
取决于您正在与之交互的对象.如果您正在与 GUI 交互,则使用 javax.swing.Timer
,否则使用 java.util.Timer
.
Depending upon what you are interacting with. If you are interacting with GUI then use javax.swing.Timer
, else use java.util.Timer
.
这是否意味着如果我正在构建一个 GUI,我必须使用 Swing 版本计时器?
Does this mean if I'm building a GUI I have to use the swing version for a timer?
是
这篇关于为什么 Java 中有两个 Timer 类(一个在 javax.swing 下,一个在 java.util 下)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!