Creating a Timer for a Swing GUI Application

     

These timers are terrific , but they are meant for executing the kinds of tasks we mentioned ”performing maintenance or doing some kind of transfer or other programmatic function. There is a different, related timer class for use in Swing applications. Don't start to panic because now there's even more about this when you didn't really care that much to begin with you just wanted a little timer and now you have to read all this junk but don't worry it will be okay. The functionality that is provided by the Swing timer and the java.util.Timer class are pretty much the same. There are a couple of differences.

  • The Swing timer is useful if you are building a Swing app and don't need a bunch of timers. The util Timer class is scalable up to thousands of tasks, whereas you don't want to use the Swing timer for more than oh 25 or so.

  • The main difference in terms of implementation is that Swing timers can schedule tasks to run on your GUI's event thread, because they all share that thread. Although you can subclass java.util.TimerTask and call the EventQueue.invokeLater() method to replicate this functionality, it is built in with the Swing timer.

Here's how you do it:

  1. Create an object of type javax.swing.Timer.

  2. Register an action listener on it.

  3. Start the timer using the start() method.

The following code creates a timer and starts it up. After the elapsed delay, an action event is fired every delay (here, every two seconds). The second argument to the Timer constructor represents the guy who will do the work ”an ActionListener .

 

 int delay = 2000; // two seconds  ActionListener worker = new ActionListener() {        public void actionPerformed(ActionEvent evt) { //do some task        }    };  new Timer(delay, worker).start(); 

This event firing business will continue until someone puts it out of its misery by calling stop() . On the other hand, if you want it to execute only once, you can call the timer's setReapeats(false); method.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net