jasa pembuatan repository kampus

Using Timers in Java

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, that’s 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(); //There is also tmrTest.stop(). tmrTest.pause(), and a few more methods such as finding the current count time and setting the speeds.

Next up is the action listener, this exists within the main class and is allowed to run along side the class.

ActionListener myTimer = new ActionListener() //Notice how it has the name of the second timer parameter, not the timer name!{public void actionPerformed(ActionEvent evt){//Do whatever you want to execute every millisecond


And that’s 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!

Overall this is a much easier method than multi threading. It allows you to set the time manually instead of the constant need for counter variables within threads. Also, the set time will run the same on any system running it, threads will run as fast as the current processor allows. This means that a computer with a better processor will allow the thread to run faster than one without, this may cause problems within your application.

%d bloggers like this: