To make the single codebase work as both applet and application, I extend my game from the applet class and add a canvas to it. Here’s my game structure.
public class MyGame extends JApplet implements Updateable, Runnable {
private Canvas canvas = null;
public static BufferStrategy buffer = null;
// Start the game
public final void start(){
canvas = new Canvas();
add(canvas);
canvas.setIgnoreRepaint(true);
canvas.requestFocus();
canvas.createBufferStrategy(2);
buffer = canvas.getBufferStrategy();
// Finalize the VM
System.gc();
System.runFinalization();
// Panel settings
setFocusable(true);
running = true;
// Start the game loop in new thread
Thread th = new Thread(this);
th.start();
}
}
And I render like this.
Graphics2D g = (Graphics2D)buffer.getDrawGraphics();
render(g);
g.dispose();
buffer.show();
It works as an applet perfectly. To make it work as an application, I added the same applet to a jframe.
public static void main(String[] args){
JFrame f = new JFrame("My Game");
setUndecorated(true);
setResizable(false);
setSize(width, height);
MyGame game = new MyGame();
f.add(game);
f.setVisible(true);
game.start();
}
This code opens a window. The sounds are heard which indicates that the game is running but the canvas is invisible.
Thanks