I have a program that is just a window that draws something (no calculations, no interaction with the user etc). This program's main JPanel has a fairly complex paintComponent function - it takes about 5 to 10 ms to perform.
I set up a Timer that calls a TimerTask every 25 ms. That TimerTask just calls repaint() on the panel. That way the program should have 40 FPS.
But the panel's paintComponent method takes about 5 to 10 ms to perform. For some reason, the Timer waits for the TimerTask's run() method to complete (meaning that it waits for the panel to repaint). This way it's not repainted every 25 ms, but 30-35 ms, leading to unstable and bad FPS.
Obviously I want the calculations to be performed in the background - now the program just performs the drawing and then waits idly for 25 ms, instead of performing drawing and waiting just the remaining time.
I've tried using a swing.Timer instead of a util.Timer, that didn't work (it was the same).
I tried having two separate timers, one for drawing the graphics on a BufferedImage and a different one for putting the BufferedImage on the JPanel. That was a bit better performance-wise but flickered.
So how do I draw graphics truly in the background?