How to prevent screen tearing when using triple buffering in Java

104 Views Asked by At

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();
    }
}
0

There are 0 best solutions below