Search code examples
java2d-games

cannot switch panels for my game


The game I am building involves switching panels after the start button is clicked when startGame() is called. The program freezes once the button is clicked and does nothing.

Here is code snippet:

public class ArtilleryGame extends JFrame {
    private static final long serialVersionUID = 1L;
    //TODO: fix clouds from updating with background

    static StartPanel startPanel = new StartPanel();
    public ArtilleryGame() throws InterruptedException
    {
        setSize(898,685);
        setLocationRelativeTo(null);
        setTitle("Tank Game");
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        URL sound = this.getClass().getResource("Sounds/Intro_Screen.wav");

        AudioClip drop = Applet.newAudioClip(sound);
        drop.loop();
        drop.play();

        add(startPanel);
        //add(new GamePanel());
        buttons();

        setVisible(true);
    }
    private void buttons()
    {
        URL startURL = this.getClass().getResource("imgg/StartBtn.png");
        BufferedImage startI = new BufferedImage(170, 62, BufferedImage.TYPE_INT_RGB);
        try
        {
            startI = ImageIO.read(startURL);
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        ImageIcon startImg = new ImageIcon(startI);

        JButton startBtn = new JButton(startImg);
        startBtn.setSize(170, 62);
        startBtn.setBorder(BorderFactory.createEmptyBorder());
        startBtn.addActionListener(new ActionListener()
        {

            @Override
            public void actionPerformed(ActionEvent e)
            {
                startGame();
            }
        });

        startBtn.setLocation(365, 310);
        StartPanel.background.add(startBtn);
    }

    public void startGame()
    {
        remove(startPanel);
        add(new GamePanel());
    }

    public static void displayCredits()
    {
        JOptionPane.showMessageDialog(null, new CreditsPanel(), "Tank Game", JOptionPane.PLAIN_MESSAGE);
    }
    public static void main(String[] args) throws InterruptedException
    {
        new ArtilleryGame();
        //displayCredits(); 
    }   
}

Solution

  • Use a CardLayout. The CardLayout allows you to easily swap panels.

    Read the section from the Swing tutorial on How to Use CardLayout for more information and working examples.