Upcoming Events
Southwest Gaming Expo
11/20 - 11/22 @ Dallas, TX

Workshop on Network and Systems Support for Games (NetGames 2009)
11/23 - 11/25 @ Paris, France

ICIDS 2009 Interactive Storytelling
12/9 - 12/11 @ Guimarães, Portugal

Global Game Jam
1/29 - 1/31  

More events...


Quick Stats
6536 people currently visiting GDNet.
2341 articles in the reference section.

Help us fight cancer!
Join SETI Team GDNet!



Link to us

Link to us

  Intel sponsors gamedev.net search:   

Java Games: Active Rendering


Active Rendering in a Window

The first thing needed is a window. The important thing to note is the call disabling paint notifications. When doing active rendering, there is no need to let the operating system call the paint method.

// Create game window...
JFrame app = new JFrame();
app.setIgnoreRepaint( true );
app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
If we just set the size of the JFrame, some of the drawing area will be lost to the window border and title bar. By using a canvas of the correct size, the JFrame is forced to show the entire area.

Remember - do not forget to ignore repaint on the canvas!

// Create canvas for painting...
Canvas canvas = new Canvas();
canvas.setIgnoreRepaint( true );
canvas.setSize( 640, 480 );
		
// Add canvas to game window...
app.add( canvas );
app.pack();
app.setVisible( true );
The next step is to create the buffer strategy. Java has a handy class that uses blitting if in windowed mode, or page-flipping if full screen. I will be demonstrating a full screen application a little later, so for right now, let's stick with the Window...
// Create BackBuffer...
canvas.createBufferStrategy( 2 );
BufferStrategy buffer = canvas.getBufferStrategy();
After the Buffer Strategy has been created, it can be used to create a graphics object for drawing. Calling the show method performs the blitting or page-flipping, so the animation is smooth. Because the off-screen surface could be lost at any time, it is important to make sure the content is not lost before showing the image. See the Javadocs for the Buffer Strategy for more information. Java recommends wrapping the render calls in a try/finally block so that the graphics object can be disposed even if an exception is thrown from the render loop.

Remember - when using active rendering, the dispose() method needs to be called on the graphics object.

Graphics graphics = null;
while( true ) {
  try {
    // clear back buffer...
    graphics = buffer.getDrawGraphics();
    graphics.setColor( Color.BLACK );
    graphics.fillRect( 0, 0, 639, 479 );

    // Draw stuff here using Java's Graphics Object!!!

    // blit the back buffer to the screen			
    if( !buffer.contentsLost() )
      buffer.show();
      
    // Let the OS have a little time...
    Thread.yield();
  } finally {
    if( graphics != null ) 
      graphics.dispose();
  }
}
The following code is a complete example of Active Rendering. This program draws a bunch or rectangles on the screen and looks just like the program in Figure 2. It also creates a BufferedImage for drawing, and keeps track of frames-per-second.
import java.awt.*;
import java.util.Random;
import javax.swing.JFrame;

/*
 * This is an example of a simple windowed render loop
 */
public class SimpleWindowedGame {

  public static void main( String[] args ) {
		
    // Create game window...
    JFrame app = new JFrame();
    app.setIgnoreRepaint( true );
    app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
		
    // Create canvas for painting...
    Canvas canvas = new Canvas();
    canvas.setIgnoreRepaint( true );
    canvas.setSize( 640, 480 );
		
    // Add canvas to game window...
    app.add( canvas );
    app.pack();
    app.setVisible( true );
		
    // Create BackBuffer...
    canvas.createBufferStrategy( 2 );
    BufferStrategy buffer = canvas.getBufferStrategy();

    // Get graphics configuration...
    GraphicsEnvironment ge = 
        GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();
    GraphicsConfiguration gc = gd.getDefaultConfiguration();

    // Create off-screen drawing surface
    BufferedImage bi = gc.createCompatibleImage( 640, 480 );

    // Objects needed for rendering...
    Graphics graphics = null;
    Graphics2D g2d = null;
    Color background = Color.BLACK;
    Random rand = new Random();
		
    // Variables for counting frames per seconds
    int fps = 0;
    int frames = 0;
    long totalTime = 0;
    long curTime = System.currentTimeMillis();
    long lastTime = curTime;
		
    while( true ) {
      try {
        // count Frames per second...
        lastTime = curTime;
        curTime = System.currentTimeMillis();
        totalTime += curTime - lastTime;
        if( totalTime > 1000 ) {
          totalTime -= 1000;
          fps = frames;
          frames = 0;
        } 
        ++frames;

        // clear back buffer...
        g2d = bi.createGraphics();
        g2d.setColor( background );
        g2d.fillRect( 0, 0, 639, 479 );
				
        // draw some rectangles...
        for( int i = 0; i < 20; ++i ) {
          int r = rand.nextInt(256);
          int g = rand.nextInt(256);
          int b = rand.nextInt(256);
          g2d.setColor( new Color(r,g,b) );
          int x = rand.nextInt( 640/2 );
          int y = rand.nextInt( 480/2 );
          int w = rand.nextInt( 640/2 );
          int h = rand.nextInt( 480/2 );
          g2d.fillRect( x, y, w, h );
        }
				
        // display frames per second...
        g2d.setFont( new Font( "Courier New", Font.PLAIN, 12 ) );
        g2d.setColor( Color.GREEN );
        g2d.drawString( String.format( "FPS: %s", fps ), 20, 20 );
				
        // Blit image and flip...
        graphics = buffer.getDrawGraphics();
        graphics.drawImage( bi, 0, 0, null );
        if( !buffer.contentsLost() )
          buffer.show();
				
        // Let the OS have a little time...
        Thread.yield();
      } finally {
        // release resources
        if( graphics != null ) 
          graphics.dispose();
        if( g2d != null ) 
          g2d.dispose();
      }
    }
  }
}




Full Screen Active Rendering

Contents
  Active Rendering Overview
  Active Rendering in a Window
  Full Screen Active Rendering

  Printable version
  Discuss this article