How to restart application using JOptionPane?

1.6k views Asked by At

So when a player dies in my game, I want a popup to ask if they want to restart or exit. The NO and CANCEL options work fine (System.exit(0)) but the YES option is where I am having troubles. I call the main game when YES

   private void playerHealth() {
        JDialog.setDefaultLookAndFeelDecorated(true);
        if (player.health <= 0) {
            int response = JOptionPane.showConfirmDialog(null, "Do you want to continue?", "Confirm",
                    JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (response == JOptionPane.NO_OPTION) {
                System.exit(0);
        } 
            else if (response == JOptionPane.YES_OPTION) {
                new Game().start();
        } 
            else if (response == JOptionPane.CLOSED_OPTION) {
                System.exit(0);
        }
     }
 }  

using a line from my Launcher Class

package core;

public class Launcher {

    public static void main(String[] args){
        //Launches new Game
            new Game().start();    
    }    
}

and it restarts, but the popup doesnt go away. The game cannot be played again, I have to exit and start it again. It would be good if someone can figure out a way stop the prompt to popup again and again after clicking YES.

Thank you

Edit: I put

player.health = 100;

in the code:

else if (response == JOptionPane.YES_OPTION) {
     player.health = 100;
     new Game().start();
    } 

and this seems to fix the problem. However, I now have a completely different problem in that a new app is started every time and the old is not deleted. Is there a way to delete the old and start a new game?

Thanks

2

There are 2 answers

3
maskacovnik On

Look at health variable.
If you told the popup shows again, this condition:

player.health <= 0

has to be true after restart. Because of this I expect player or health variable is static and static variables has to be restarted too

3
Laurent B On

I think the problem is not in the code of your playerHealth method. This should work perfectly fine.

The problem is that probably elsewhere in your code you keep calling back playerHealth.

Maybe you should consider passing the game instance to your player health and call a game.restart() that should stop calling the playerHealth method and restart altogether your game (maybe through game.start()).

To conclude, your code is good but most probably your are doing the call to playerHealth wrong somewhere.

Edit : if you want to use a pattern such as Observer to notify the Game instance it needs to stop, have a look at this post: Examples of GoF Design Patterns in Java's core libraries

Especially the ActionListener instances.