It’s finally time to create the rendering loop mentioned previously. A new class will be created that implements the Runnable interface, and the rendering loop will be controlled by a thread. The startRenderThread() method starts the rendering loop and stopRenderThread() causes it to stop and the thread to die. The thread can be temporarily paused by calling the pauseRenderThread() method.
The run method contains the rendering loop. The loop is just as discussed previously, with a few extras—stopping and pausing the rendering thread as well as handling the possibility of corruption of our rendered frames. The corruption issue will be discussed in the section on volatile images. The doRender() method, which is called each time through the loop, simply gets the Graphics object handle from the buffer strategy and passes it to the render method. The default render() method clears the back buffer to the background color and then returns. This method is overridden to call all the game logic and to perform the game rendering.
public void run() { boolean contentsLost = false; try { // get the buffer strategy that we set up BufferStrategy bs = getBufferStrategy(); // Stay in the render thread until it is stopped while(doRender) { // if paused then don’t do anything if(!pauseRender) { // perform the rendering for the new frame doRender(); // Because the buffer strategy may have used volatile // images to speed things up make sure that // the frame buffer just rendered has not // been corrupted or lost if(bs.contentsLost()) contentsLost=true; // If the buffer has been corrupted or lost then we // don’t want to show the contents of it yet. We // will go through the loop again and redraw the frame. if(contentsLost) { if(bs.contentsRestored()) contentsLost=false; } else { // Things are okay,swap the buffers to show the frame bs.show(); } } //Sleep for a bit and keep the frame rate static. Thread.sleep(renderLoopSpeed); } } catch(Exception x) { x.printStackTrace(); } } public boolean doRender() { boolean shouldSwap = render(getBufferStrategy().getDrawGraphics()); return shouldSwap; }
On the CD In the code provided, the FullScreenFrame2 renders using the page-flipping technique. It was adjusted to draw random-size rectangles of random color at slow intervals. When it’s running properly, it will look something like that shown in Figure 3.7.
Figure 3.7: Page flipping some color rectangles of random color. (See color version on companion CD-ROM.)