16.9. Timers

Timers are useful for numerous tasks, including image animation, starting and stopping simulations, and timing out secure network connections. The previous section (Animating Images) illustrated the capability of animating images by creating a user-defined thread that periodically invokes a specified action and then goes to sleep. To simplify this common and useful task, a robust Timer class, javax.swing.Timer, was added to the Swing package. A Timer can run for a single cycle or be set to ring periodically.

Creating a Swing Timer is as simple as instantiating a Timer object, specifying the period in milliseconds that the Timer should fire an ActionEvent and specifying a listener that should receive the event. Once the timer is created, ...

Get Core Web Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.