Search code examples
javaswingtimerjoptionpane

Applying restart, close, and adjustment functions to specific options for JOptionPane


I created a option pane that displays when my game ends. I am using Java swing.

How would I make a function that "quits" the game, another one that "restarts" the game, and one that adjusts a timer speed? Im not sure how to implement with Object[] options array.

Object[] options = { "Restart Game", "Change Game Difficulty",
                    "Exit Game" };

            int n = JOptionPane.showOptionDialog(gamePanel,
                    "GAME OVER - Your Hit Yourself and Died! ",
                    "Game Over!", JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.WARNING_MESSAGE, null, options, options[2]);

Solution

  • From the Java Docs for JOptionPane.showOptionDialog(..) (which I suggest you bookmark, and read carefully before asking questions on SO).

    Returns:

    an integer indicating the option chosen by the user, or CLOSED_OPTION if the user closed the dialog

    Other notes:

    int n = JOptionPane.showOptionDialog(gamePanel,
            "GAME OVER - Your Hit Yourself and Died! ",
            "Game Over!", JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.WARNING_MESSAGE, null, options, options[2]);
    
    1. JOptionPane.YES_NO_CANCEL_OPTION best to stick with the simpler OK_CANCEL_OPTION.
    2. JOptionPane.WARNING_MESSAGE How is this a warning? Use JOptionPane.QUESTION_MESSAGE instead.