Reputation: 11
I am following the intermediate java tutorial found at
https://www.youtube.com/watch?v=M2GoiOas2u8&list=PL54DB126285ED0420 .
But I am having issues with the double buffering flickering.
my relevant code in two of my classes is as follows
GamePanel.Java
private void gameRender()
{
if (dbImage == null) // create the buffer
{
dbImage = createImage(GWIDTH, GHEIGHT);
}
if (dbImage == null)
{
System.err.println("dbImage is still null!");
return;
}
else
{
dbg = dbImage.getGraphics();
}
// Clear the screen
dbg.setColor(Color.WHITE);
dbg.fillRect(0, 0, GWIDTH, GHEIGHT);
// Draw Game elements
draw(dbg);
}
// Draw all game content in this method
public void draw(Graphics g)
{
world.draw(g);
}
private void paintScreen()
{
Graphics g;
try
{
g = this.getGraphics();
if (dbImage != null && g != null)
{
g.drawImage(dbImage, 0, 0, null);
}
Toolkit.getDefaultToolkit().sync(); //For some OS.
g.dispose();
}
catch(Exception e)
{
System.err.println(e);
}
}
World.Java
public void draw(Graphics g)
{
for (int i = 0; i < arrayNumber; i++)
{
g.drawImage(blockImg[i], blocks[i].x, blocks[i].y, null);
}
}
Where arrayNumber = 1200. This program only has flickering issues when the map is moved to the right or down, (meaning that blocks.x and blocks.y increase for each value of i), but not the other way around. I tried drawing from the bottom right up by replacing each [i] with [arrayNumber - i] and modifying the parameters of the for loop. This made the flickering only occur when moving the map up and to the left.
So I know that I should somehow modify this run method in the world class to somehow use double buffering, but was wondering how I would go about doing so since world doesn't extend JPanel?
Upvotes: 1
Views: 477
Reputation: 347194
Don't use this.getGraphics();
, this is not how painting in Swing is done.
Swing uses a passive painting algorithm, which means you do not control the painting process. Swing will make decisions about what and when something should be painted.
Swing components are already double buffered by default.
Instead of fighting this, you should understand and embrace it.
Start by overriding paintComponent
of you GamePanel
and render your game state here (don't forget to call super.paintComponent
)
Take a look at Performing Custom Painting and Painting in AWT and Swing for more details about how painting is achieved in Swing
Upvotes: 1