BufferStrategy doesn't work in Applet

Ah, it’s been a while since I started a new Thread on JGO.
Well here I go:

I’ve been using JApplet for a long time. Now I decided that Swing isn’t really necessary when I want to make a game that takes full control of the entire window so I decided to switch to Applet. However, it is not working! I thought I must have a bug somewhere in my game code that prevents this so instead of debugging my entire game, I made a simple test case:


import java.applet.Applet;
import java.awt.Canvas;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;

public class Test extends Applet implements Runnable {
	private static final long serialVersionUID = -5975037209475083278L;
	
	private Canvas canvas;
	
	public void init() {
		setSize(500,500);
		
		setIgnoreRepaint(true);
		
		canvas = new Canvas();
		add(canvas);
		canvas.createBufferStrategy(2);
	}
	
	public void start() {
		new Thread(this).start();
	}
	
	public void run() {
		BufferStrategy strategy = canvas.getBufferStrategy();
		
		long time = 0;
		int frames = 0;
		
		while(true) {
			if(System.nanoTime() >= time+1e9) {
				System.out.println(frames);
				frames = 0;
				time = System.nanoTime();
			}
			
			frames++;
			
			try {
				do {
					do {
						Graphics2D g = (Graphics2D)strategy.getDrawGraphics();
						
						g.fillRect(50, 50, 100, 100);
						
						g.dispose();
					}while(strategy.contentsRestored());
					
					strategy.show();
				}while(strategy.contentsLost());
			}
			catch(Exception exc) {
				exc.printStackTrace();
			}
		}
	}
}

And sure enough! Try it yourself and see. I tested this in the browser and in the applet viewer. Nothing shows up.
I’m on Windows 7 64-bit using the latest and greatest Java 6 Update 26

However, extend JApplet instead of Applet and, voila, it works magnificently :slight_smile:

I’m clueless so any explanations and/or workarounds are appreciated :smiley:

I find anything more complex then the Swing timer to be a bit above my head at this point. But this site has been extremely useful to me. If you can’t find better advice perhaps the Util timer might be the way to go?

http://zetcode.com/tutorials/javagamestutorial/animation/

I’ve been reading this Java 1.4 Game Programming book and they state that the Swing library was meant to be a replacement for the AWT library. Now i can’t confirm the validity of this claim, but i am curious. Why wouldn’t you want to use the Swing Library?

canvas.setSize(getWidth(), getHeight());

Sinuath, Swing adds extra overhead when I don’t want to use it for a game.

zoto, O_O no way! Why did it automatically resize itself in JApplet and not in Applet? Thanks a ton! :slight_smile:

JApplet contains a content pane with a default LayoutManager of BorderLayout. java.awt.Applet’s default layout is FlowLayout.

Ohh I didn’t know Applet’s default layout was FlowLayout. Thanks!