Why are there two Timer classes in Java(one under javax.swing, one under java.util )?
java, swing, timer
Solution
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.
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
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
Problem
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!