mbohun
5/2/2013 - 3:03 AM

an example of double-buffering using java.awt.image.BufferStrategy

an example of double-buffering using java.awt.image.BufferStrategy

<html>
  <body bgcolor='434572'>
    <table align='center'>
      <tr></tr>
      <tr>
	<td></td>
	<td>
		<applet archive ="appletgame.jar" 
			code="TestAppletCanvasBufferStrategy.class" 
			width="800" height="600">

                  <!-- no difference -->
		  <param name="java_arguments"
			 value="-Dsun.java2d.opengl=true">
		  </param>

		  <param name="test.param.one" value="666" />
		</applet>
	</td>
	<td></td>
      </tr>
      <tr></tr>
    </table>

  </body>
</html>
import java.applet.Applet;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;

public class TestAppletCanvasBufferStrategy extends Applet {
  
    public void init() {
	this.canvas.setSize(WIDTH, HEIGHT);
	this.add(this.canvas);
	this.canvas.createBufferStrategy(2);
    }
 
    public void start() {

	isRunning = true;

	final Runnable r = new Runnable() {
		public void run() {
		    long time = 0;
		    int frames = 0;
		    int x = 0;
		    final Canvas c = canvas;

		    while (isRunning) {
			final BufferStrategy strategy = c.getBufferStrategy();

			do {
			    do {
				final Graphics2D g = (Graphics2D)strategy.getDrawGraphics();

				g.setColor(Color.BLUE);
				g.fillRect(0, 0, WIDTH, HEIGHT);

				g.setColor(Color.GREEN);
				g.fillRect(x, 50, 100, 100);
		    
				g.dispose();

			    } while (strategy.contentsRestored());
       
			    strategy.show();

			} while (strategy.contentsLost());

			x++;
			if (x > WIDTH) {
			    x = 0;
			} 
		    }
		}
	    };

	final Thread t = new Thread(r);
	t.start();
    }

    public void stop() {
	isRunning = false;
    }

    private volatile boolean isRunning;
    private final Canvas canvas = new Canvas();

    // we can add min/max supported width/height const-s later
    static final int WIDTH  = 800;
    static final int HEIGHT = 600;
}