Java – Timers W/Out Threads + My Birthday!
Well today (December 24th) I am another year older. Here is a special, helpful tutorial for using Timers in Java! Enjoy.
Threads can get confusing and multi-threading is no better. The use of timers is really easy and allows multiple to run at once, with different times without interference.
The first thing needed is the package to be imported:
import javax.swing.Timer;
Next, declaring the Timer:
Timer tmrTest = new Timer(1,myTimer);
The 1 is the interval in milliseconds. Meaning, this timer will execute once every millisecond, thats fast.
myTimer is just the name of the ActionListener.
Starting the timer is also necessary, it's probably best to do it in the main method.
tmrTest.start();
Next up is the action listener, this exists within the class.
ActionListener myTimer = new ActionListener() { public void actionPerformed(ActionEvent evt) { //Do whatever you want to execute every millisecond } };
And thats it. You can add as many as you want. Just be sure to rename the name of the AcitonListeners and be sure to start the timers!




Reader Comments