JFrame Image Flicker problem (Double Buffered)

Ok, so I have been working on trying to get together some simple 2D demos in Java. I have been looking at using a JFrame/JPanel combination.

I was using a Timer and implementing ActionListener and this was working well, but I saw that most people were using a Thread and implementing Runnable so that the animations would work correctly. I tried doing this myself and have got it mostly working.

What is odd is now that I have implemented double buffering I have some flicker, when without it I was getting no flicker at all. The entire image is not flickering, only when two different images are drawn on top of each other. My entire background doesn’t flicker at all. But when I try to draw my character it flickers whether it is moving or not. Almost as if java is redrawing them, but out of z-order sometimes causing a flicker.

	public void run() 
	{
		bRunning = true;	// Keep flag set
		
		// Repeat update/animation loop, sleeping a bit
		while (bRunning)
		{
			updateBoard();
			renderBoard();
			repaint();
		}
		
		try
		{
			Thread.sleep(20);	// Sleep 20 millis
		}
		catch(InterruptedException ie)
		{
			System.err.println("Error: Thread exception!");
		}
		
		System.exit(0);	// end of run
	}
	private void renderBoard()
	{
		// If null, create the buffer
		if (frameBuffer == null)
		{
			frameBuffer = createImage(WIDTH, HEIGHT);
			if (frameBuffer == null)
			{
				System.err.println("Error: frameBuffer is null");
			}
			else	// otherwise, write to Graphics2D object
				gDevice = frameBuffer.getGraphics();
		}
		
		// Draw background, using correct coordinates
		gDevice.drawImage(background, bX[0], 0, null);
		gDevice.drawImage(background, bX[1], 0, null);
		gDevice.drawImage(background, bX[2], 0, null);
		gDevice.drawImage(background, bX[3], 0, null);
		
		// Draw character on top of background
		// THIS IS WHAT FLICKERS
		gDevice.drawImage(gChar.getImage(), gChar.getX(),
						  gChar.getY(), null);
	}
	public void paintComponent(Graphics gDevice)
	{
		super.paintComponent(gDevice);
		if (frameBuffer != null)
		{
			gDevice.drawImage(frameBuffer, 0, 0, null);
		}
	}

Anyone have any ideas?

Could you give us some screenshots showing the problem?

Rough reading of the code you’ve posted would suggest you’re rendering to the buffer in your animation thread and reading from it on the Swing thread without synchronising access, so sometimes you’re writing and reading from the image at the same time! I’d suggest either going back to Timer or reading up on active rendering.

Oops forgot about this thread. I found some articles on Active Rendering myself and I was able to fix my double buffering with no flicker at all, even while running different rates of frame animation on my sprites, and my top level animation loop. It works perfectly now under all conditions so far. I just need to figure out how I can calculate my fps and output it to a string for debug now.