2
\$\begingroup\$

So I have a JFrame holding a JPanel, to which I'm drawing at about 60 FPS. I've been told that "Swing is double buffered by default", but, nevertheless I'm getting massive flickering. At first, I tried modifying the Graphics object from JPanel.getGraphics(), but was not surprised when it flickered (to black, the background colour of the game so far), as I assumed that it was redrawing when I blanked the screen. However, then I overrode paintComponent(), passing the Graphics to all objects to draw with, and made it call the super version, which I assumed would solve it, but no difference.

I'm still getting the Graphics object from the same place, i.e. JPanel.getGraphics(), because paintComponent() needs a Graphics argument. Should I be getting it from some other place? If not, what else could be causing the problem?

\$\endgroup\$

3 Answers 3

4
\$\begingroup\$

tried to activate double buffering manually (just to make sure)? setDoubleBuffered

On the other hand I always used a self writen double buffering at the (overwritten) update method. Something like that

\$\endgroup\$
1
  • \$\begingroup\$ This is a good answer, but it turns out my problem was what method I was calling in the first place. But either way, useful info, thanks. \$\endgroup\$ Commented Oct 19, 2011 at 7:35
3
\$\begingroup\$

Whoops. Looks like I should have been calling repaint(), not calling paintComponent(Graphics) directly. repaint() calls that as part of the double buffering process, so it shouldn't be called by hand if you want to avoid flickering.

\$\endgroup\$
0
\$\begingroup\$

I'm not sure what you're trying to draw onto the JPanel, but the code below worked for me to animate a sinusoidal wave. Using repaint() in the program run loop seems to hold back the flickering.

public class YourClass extends JPanel implements Runnable{
     private boolean running = true;
     // your code here
     public void run(){
         repaint(); // called repeatedly as along as program is running
         while (running){
             update(); // called preferably 60 times a second
             render(); // no limits set, depends on computer performance
         }
     }
     // your code here
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .