Canvas isn't visible

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

I think your not actually adding canvas to the jframe, i think you would need to add game.canvas.

Not really sure, I have always extended canvas, and have not really touched JFrames and that in a while

The graphics are visible when I minimize and again opened the game. Also since I’m adding the canvas to the game and adding the game to the frame, why is it not visible?

Try to add the canvas to the content pane of the JFrame.

Thanks 65K. It solved after adding the game (not the canvas) to the content pane. Do you know why it happened?