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?