I've recently been working with BufferStrategy and JFrame for preliminary graphics. However, when attempting to draw a simple rectangle to the frame, nothing appears. Here is the code:
import java.awt.*;
import java.awt.image.BufferStrategy;
import javax.swing.*;
public class GTestingMain {
public static void main(String[] args) {
JFrame myFrame = new JFrame();
Canvas myCanvas = new Canvas();
Graphics2D g;
BufferStrategy strategy;
myFrame.setSize(500, 500);
myFrame.setResizable(false);
myFrame.setLocationRelativeTo(null);
myFrame.setVisible(true);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myCanvas.setPreferredSize(new Dimension(500, 500));
myFrame.add(myCanvas);
myFrame.pack();
strategy = myCanvas.getBufferStrategy();
if(strategy == null) {
myCanvas.createBufferStrategy(3);
}
strategy = myCanvas.getBufferStrategy();//Throwing in again so strategy != null
do {
do {
g = (Graphics2D) strategy.getDrawGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 500, 500);
g.setColor(Color.red);
g.fillRect(10, 40, 50, 70);
g.dispose();
}while(strategy.contentsRestored());
strategy.show();
}while(strategy.contentsLost());
}
}
Now the problem is a little more unique. When I go into the debugger and step through the code, it works just fine. If I run normally, blank. If I click on the Frame before it is drawn to while in the debugger - blank.
I know I can 'solve' this issue with a thread, but i'd like to know why it works* in debug mode but not in a regular run. Thanks!
Before you start off with bufferStrategies, go through java doc
It says that,
What you are missing is a rendering loop basically. Also since it uses volatile images for its buffer, we never know when our video memory is lost. That explains why you were getting the rectangle in debug mode. Its like a callback system with
contentLost
andcontentsRestored
methods.Just wrap your do while loops as below.