0

I'm trying to draw a simple shape on the screen using the Swing library and the BufferStrategy class. However, when using BufferStrategy with three buffer areas, screen tearing occurs, but not when using two buffer areas. Does anyone know what's causing this behavior?

Here is my code:

import java.awt.image.BufferStrategy;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;

public class Shape extends JFrame {
    private Canvas canvas = new Canvas();

    public Shape() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1000, 800);
        setLocationRelativeTo(null);
        add(canvas);
        setVisible(true);
        canvas.createBufferStrategy(3); //    Screen tearing occurs
        // canvas.createBufferStrategy(2);    Would work properly

        while (true) {
            BufferStrategy bufferStrategy = canvas.getBufferStrategy();
            Graphics g = bufferStrategy.getDrawGraphics();
            super.paint(g);
            g.setColor(Color.blue);
            g.fillRect(0, 0, 100, 100);
            g.dispose();
            bufferStrategy.show();
        }
    }

    public static void main(String[] args) {
        new Shape();
    }
}
Abra
  • 19,142
  • 7
  • 29
  • 41
anathrax
  • 91
  • 1
  • 1
  • 11
  • 2
    https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html – Abra Feb 18 '23 at 15:08
  • 1
    You could try 4 buffers and see if that works. I don't know why you would need more than two. The `while(true)` is suspicious to me. Perhaps you need to use a `Timer` to give the buffer strategy time to work. A Swing drawing `JPanel` is double-buffered by default. – Gilbert Le Blanc Feb 18 '23 at 18:54

0 Answers0