Zhauo
Zhauo

Reputation: 27

How to use JDialog to get input

Within SpaceInvadersApp.gameEnded() (show below), how can I use JOptionPane.showInputDialog() to display a dialog following the initial Game Over message dialog to users who have won the game with a score greater than zero (isGameWon method tests this). The new dialog should inform the user that they have achieved a high score and request their name for the high score table.

 public void gameEnded() {
    String message;
    if (game.isGameWon()) {
        message = "You defeated the alien menace!  Congratulations!\n\n"
                + "Your score was " + game.getScore();
    } else {
        message = "Oh no! The aliens have defeated you.";
    }

    JOptionPane.showMessageDialog(this,
            message, "Game Over",
            JOptionPane.INFORMATION_MESSAGE);

    menuItemGamePause.setEnabled(false);
}

Upvotes: 1

Views: 1050

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

Start by taking a look at How to Make Dialogs

But basically, you could do something like...

if (game.isGameWon()) {
    message = "You defeated the alien menace!  Congratulations!\n\n"
            + "Your score was " + game.getScore();
    String name = JOptionPane.showInputDialog(this, message, "Game Over", JOptionPane.INFORMATION_MESSAGE)
    if (name != null) {
        // Save name
    }
} else {
    message = "Oh no! The aliens have defeated you.";
    JOptionPane.showMessageDialog(this,
            message, "Game Over",
            JOptionPane.INFORMATION_MESSAGE);
}

Upvotes: 3

Related Questions