I'm making a game in which the screen needs to be updated after a set of procedures (not continuously every frame) and I made a smaller program to test Graphics2D drawing. In this program, all I wanted to do was draw a small rectangle in the corner. However, the rectangle doesn't appear to draw. I'm not sure if I'm misunderstanding the use of BufferStrategy (i.e. there's a better way to update the game in this manner), but I tried calling the draw method twice to make sure the graphics2D object exists and is not null.
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import javax.swing.*;
public class test extends Canvas
{
private JFrame testWindow = new JFrame("Test");
public test()
{
createUI();
}
public static void main(String[] args)
{
new test();
}
public void createUI()
{
testWindow.setSize(500,500);
testWindow.setLayout(null);
testWindow.setLocationRelativeTo(null);
testWindow.setResizable(false);
testWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testWindow.add(this);
testWindow.setVisible(true);
draw();
draw();
}
public void draw()
{
BufferStrategy bs = this.getBufferStrategy();
System.out.println(bs);
//when the program runs this prints null once and then an identifier
if(bs == null)
{
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.RED);
g2.fillRect(10,10,100,100);
g2.dispose();
bs.show();
}
}