The following code will flush/clear the current buffer of the canvas ( a black screen will be displayed for a split second maybe and after that nothing will be displayed - which is not what I expected because I haven't stated for the buffer to be flushed )
public class Main {
static int width = 200;
static int height = 200 ;
public static void main(String[] args){
JFrame jframe = new JFrame();
Canvas canvas = new Canvas();
BufferStrategy bs;
Dimension dim = new Dimension(width,height);
canvas.setPreferredSize(dim);
jframe.setResizable(false);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.add(canvas);
jframe.pack();
jframe.setLocationRelativeTo(null);
jframe.setVisible(true);
canvas.requestFocus();
bs = canvas.getBufferStrategy();
if(bs == null){
canvas.createBufferStrategy(3);
bs = canvas.getBufferStrategy();
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0,0,canvas.getWidth(),canvas.getHeight());
g.dispose();
bs.show();
}
}
However, if the line of code bs.show() is changed into the following:
while(true){
bs.show();
}
Then the screen will be filled with black color as wanted.
Or even if we write ( I didn't add try-catch around Thread.sleep() for simplicity):
while(true){
Thread.sleep(1000);
bs.show();
}
Then the window is filled with black as wanted.
My questions:
- In the first code, why the window is flushed and the black filling of the window is not seen? does
show()clear the current buffer? ( even though I haven't told it so) and if so, then what is the time it takes for the buffer to be cleared? ifshow()indeed clears the buffer after some time then why in the third piece of code the black filling is seen no matter how much time our thread sleeps? - How do I make Bufferstrategy in the first code to continue and
show()the black filled rectangle without putting it in a loop?
Thanks!