Java buffer strategy sometimes doesn't draw properly

319 Views Asked by At

I created a game in Java which uses buffer strategy. But sometimes I just get a white frame or a white border. That happens about every fifth time. I searched a lot but I really can't figure out what I'm doing wrong. The code compiles and there aren't any errors printed out.

If if fails, the frame looks for example like that:

white border

completely white frame

Here's code (only the relevant parts):

private BufferStrategy bs;
public Testclass(){
    setResizable(false);
    setSize(1000,600);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setIgnoreRepaint(true);
    setVisible(true);
    createBufferStrategy(2);
    bs = getBufferStrategy();
}

protected void paint() {
    do {
        Graphics2D g=null;
        try {
            g = (Graphics2D) bs.getDrawGraphics();
            g.setColor(Color.CYAN);
            g.fillRect(0, 0, this.getWidth(), this.getHeight());
        } finally {
            g.dispose();
        }
        bs.show();
    } while (bs.contentsLost());
}

public static void main(String[] args) {
    Testclass window = new Testclass();
    window.paint();
}
1

There are 1 best solutions below

2
On

I actually found a better way try this:

   boolean BufferStrategyRunning = true;

    while(BufferStrategyRunning == true) {

        BufferStrategy BS = GUIFrame.getBufferStrategy();

        if(BS == null) {
        GUIFrame.createBufferStrategy(3);
        continue;
        }

        Graphics g = BS.getDrawGraphics();

        g.drawImage(CurrentScreen.BackgroundImage, 0, 0, null);
        g.dispose();
        BS.show();


    }