Why do we get the Java BufferStrategy Flickering?

364    Asked by Manishsharma in Java , Asked on Oct 11, 2022

I was watching a tutorial on using a BufferStrategy in Java and I wanted to test a very simple example. The issue is that it flickers intensely and it seems as if a piece of the starting oval stays on the screen. I know that the loop is a very bad practice but I just wanted to very simply test the BufferStrategy.

import javax.swing.*; import java.awt.*; import java.awt.image.BufferStrategy; public class Game extends JFrame { private Canvas canvas = new Canvas(); public Game() { setBounds(0, 0, 1280, 720); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); add(canvas); setVisible(true); canvas.createBufferStrategy(3); BufferStrategy bufferStrategy = canvas.getBufferStrategy(); int x = 0; int i = 0; while(true) { i++; if(i == 10) { i = 0; x++; } bufferStrategy = canvas.getBufferStrategy(); Graphics g = bufferStrategy.getDrawGraphics(); super.paint(g); g.setColor(Color.RED); g.fillOval(x, 200, 50, 100); g.dispose(); bufferStrategy.show(); } } public static void main(String[] args) { new Game(); } }
Answered by Manish kumar

You get the Java BufferStrategy flickering because you do not clear the screen after each frame. Add this after you set your graphics object.

g.clearRect(0,0,width,height);

Plus you do not need to call the super.paint() method either.



Your Answer

Interviews

Parent Categories