Note that there are some explanatory texts on larger screens.

plurals
  1. POFlicker-free JComponent rendering within a Swing event handler
    text
    copied!<p>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.</p> <p>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:</p> <pre><code>getRootPane().getContentPane().update(getGraphics()); try { Thread.sleep(25); } catch (Exception e) { } </code></pre> <p>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.</p> <p>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?</p> <p>(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!)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload