Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping a Swing timer when a component is hidden

I have a Swing timer (javax.swing.Timer) which is used to perform some animation within a custom Swing component.

However, this is causing problems - in particular it seems to stop the application from terminating because of the live timer thread even after all windows are closed. Also it would be nice to avoid the overhead of timers running on hidden objects when the animation cannot be seen.

Ideally I'd like to do the following:

  • Stop the timer when the component is hidden
  • Start the time again whenever the component becomes visible

Is this possible to do (in a thread-safe way of course!)

like image 460
mikera Avatar asked Sep 16 '12 11:09

mikera


1 Answers

I am skeptical of your first premise: this simple counter-example shows that a running javax.swing.Timer does not preclude EXIT_ON_CLOSE. The package-private, shared javax.swing.TimerQueue starts a daemon thread, which allows Program Exit. You may be understandably reluctant to rely on this implementation detail, but it may be worth looking for another reason your program fails to exit.

If defer to @kleopatra on AncestorListener; it should allow you to control the Timer as desired. The duty cycle of a component animation is typical fairly light, and it's usually dominated by rendering; the latter's overhead is small when the component is not visible. It may be worth profiling to verify that the proposed optimization is worth the effort. If so, consider a WindowListener to minimize activity in an inactive or iconified window.

Addendum: A now deleted answer suggested overriding setVisible() to condition the timer. While superficially appealing, the approach is brittle and scales poorly. The listener approach leverages the observer pattern commonly used in Swing architecture.

like image 111
trashgod Avatar answered Sep 28 '22 13:09

trashgod