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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public class MyGame extends JApplet implements Updateable, Runnable {
private Canvas canvas = null; public static BufferStrategy buffer = null;
public final void start(){ canvas = new Canvas(); add(canvas); canvas.setIgnoreRepaint(true); canvas.requestFocus(); canvas.createBufferStrategy(2); buffer = canvas.getBufferStrategy(); System.gc(); System.runFinalization(); setFocusable(true); running = true; Thread th = new Thread(this); th.start(); }
} |
And I render like this.
1 2 3 4
| 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.
1 2 3 4 5 6 7 8 9 10
| 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