Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+17 votes
asked in CSC211_Winter2018 by (1 point)

2 Answers

+11 votes
 
Best answer

There actually is an approach that can completely remove flickering, but it's a bit tricky, so I only tend to tell students about if if they ask.

The technique is known as "double-buffering", because it involves having an offscreen image (buffer) where you do all of your graphics work first, and then you use one command to draw that whole image onto your panel without clearing first.

Here's some example code, to show you how it works.

	DrawingPanel panel = new DrawingPanel(800,600);
	Graphics panelG = panel.getGraphics();
	BufferedImage bufImage = new BufferedImage(800,600, 
							BufferedImage.TYPE_INT_RGB); 
	Graphics bufG = bufImage.getGraphics();
	
	for (int i = 0; i < 100; i++) {			
		bufG.setColor(Color.WHITE);
		bufG.fillRect(0, 0, 800, 600);
		bufG.setColor(Color.BLACK);
		bufG.fillOval(i*8, 0, 100, 100);
		panelG.drawImage(bufImage, 0, 0, null);
		panel.sleep(100);			
	}
answered by (508 points)
+1

I will try doing this later when I work on my programming assignment. Thank you!

+1

Thank you! This will make animation so much smoother.

+8 votes

Honestly, this is one of the greatest obstacles I come across when it comes to Java animation (specifically the Chase and Nifty projects...). My advice is this:

  • Have the DrawingPanel sleep for longer periods of time, or don't use panel.clear() so often.
  • Keep an eye on how many objects you're animating at one time. If your program is drawing lots of objects every 20 milliseconds, chances are it'll struggle to produce all of it in the finite amount of time you give it to render.
  • Avoid writing repetitive code (D on't R epeat Y ourself). If your program is spending more time running through your methods than it needs to, it will take more time to draw everything on the DrawingPanel. (We're talking nanoseconds or something at this point, but still.)
answered by (1 point)
...