Search code examples
javaswingappletjpaneljapplet

How to switch between JPanels in an applet?


How do I switch between JPanels in an applet? Switching between JPanels in a JFrame is very easy and I do it like this:

        frame.remove(mainMenu); //remove the old jpanel
        frame.add(game); //add the new jpanel
        game.createImage(); //runs createVolatileImage(width, height)
                            //in the other class (JPanel)
        frame.revalidate();
        frame.repaint();
        requestFocus();

However, how do I replicate this in an applet? When I try this in an applet, I get a nullPointerException when I try to run image.getGraphics() on the image that I created in the new JPanel.


Solution

    1. The best way to switch JPanels is to use a CardLayout (tutorial). If done correctly, this will work whether your GUI is a JFrame, JDialog, JApplet,... et.
    2. Your NullPointerException likely has nothing to do with your swapping views. To debug this will require more information on your part.
    3. It is likely due to your image variable being null, perhaps due to trying to read it in as a File rather than as a resource.