I'm writing a simple Java Swing application that is designed as a demo for a course. The purpose of the program is to visualize the progress of a recursive method (specifically, a recursive solution to a maze). I'd like to be able to update the appearance of the JComponent as the recursive method executes, so from the perspective of Swing the updates can't be triggered individually from a Timer class, which I gather is the usual method for animations.
My first thought was just to call repaint() whenever I want to redraw the visualization. But the recursive method itself is called in the event handler of a JButton, which means all the calls to repaint() are delayed until the event handler terminates -- and all I get to see is the last frame of the animation. I found that I can get the drawing to happen immediately if I call update() instead, like this:
getRootPane().getContentPane().update(getGraphics());
try {
Thread.sleep(25);
} catch (Exception e) {
}
This almost works, except that the animation flickers. I know that Swing is double-buffered, but apparently getGraphics gives me the active buffer rather than the back buffer. I can't see any methods that would give me access to the back buffer.
So I'm looking for a solution that would allow me to repaint the component in the middle of the recursion and give me a flicker-free animation. Is there a way to activate the built-in double-buffering while an event handler is executing? Would it be better to try to implement my own buffering system? Or is what I'm trying to do just not possible/advisable with Swing?
(As a final note, this is my first post here. I've tried to write a good question, but if I'm missing anything please let me know nicely and I'll try to do better next time. Thanks!)