java timer类两个timer,为什么Java中有两个Timer类(一个在javax.swing下,一个在java.util下)?...

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?

thanks!

解决方案

Here is the difference between javax.swing.Timer and java.util.Timer:

javax.swing.Timer

suitable for simpler cases, using low numbers of timers (say less than a dozen)

runs ActionListener objects on the event dispatch thread

can directly update the GUI, without using EventQueue.invokeLater

if the task runs entirely in the event dispatch thread (that is, if it does not spawn a worker thread), then the GUI will remain responsive only if the task does not take very long (say under 300 milliseconds)

java.util.Timer

more scalable than javax.swing.Timer, and with additional scheduling features

runs TimerTask objects on a private thread

needs to use EventQueue.invokeLater to update the GUI

You can use Swing timers in two ways:

To perform a task once, after a delay.

For example, the tool tip manager uses Swing timers to determine when to show a tool tip and when to hide it.

To perform a task repeatedly.

For example, you might perform animation or update a component that displays progress toward a goal.

Which one should I use if I want to simply run X every Y seconds?

Depending upon what you are interacting with. If you are interacting with GUI then use javax.swing.Timer , else use java.util.Timer.

Does this mean if I'm building a GUI I have to use the swing version

for a timer?

YES

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值