2

I have a project written using Swing, and I want to make it more smoothly (like JavaFX is) by adding animation to some components(JButton, JScrollPane, JSplitPane) using javax.swing.Timer.

UPD: That is not a game. I want to use the Timer for short animations like mouseHover events or dropdown, or scroll. But the problem is, a lot of Timer objects should be created.

Question: What action does it perform for JVM? I would start and stop a lot of Timers during app session.

SeniorJD
  • 123
  • 7

3 Answers3

1

Yes if you wanna do the animation yourself, javax.swing.Timer is your best option. It is lightweight and guarantees your code executes on the EDT thread. If you venture into the depths of swing components like JScrollPane you might encounter javax.swing.Timer being used for things like auto scrolling during drag and drop etc. In short animation in swing is quite possible but rare in standard components. Just keep your redraw area to the minimum and repaint wisely. I would advocate looking into timing framework though.

1

https://stackoverflow.com/questions/15040989/issues-creating-a-very-accurate-swing-timer Shows swing timer being off dead accurate time by 10ms to 200ms using it to trigger frames of animation won't work well. Using it to trigger the start of an animation should be OK. The way swing timers work is one thread manages the timeouts and the actual event callback happens on the EDT so it shouldn't matter if you have a large number of timers they don't use that many resources, just make sure the EDT can keep up.

stonemetal
  • 3,381
0
  1. No. Run your app with something akin to a game loop and update your components periodically that way. With a timer, you're going to get unreliable and choppy animation. This topic is too big to cover in detail here, but that's the basic idea.
  2. Implementing animation with Swing is fine, but just don't use a timer.

HTH