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:
Is this possible to do (in a thread-safe way of course!)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With