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