user3529351
user3529351

Reputation: 43

How to get the value of option selected from JOptionPane.showMessageDialog?

I am making a java game. This is a piece of my code in which I have a question.

How to get the value (no matter index value or string value) of option selected? I have to use it later in my code, for instance if(n="5 point game") { do this}

newgame=new JButton("NEW GAME");
newgame.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
      Object[] options = {"5 point game",
            "Non stop game"};
      int n = JOptionPane.showOptionDialog(newgame,
                                           "Choose a mode to play ",
                                           "New Game",
                                            JOptionPane.YES_NO_OPTION,
                                            JOptionPane.QUESTION_MESSAGE,
                                            null,     //do not use a custom Icon
                                            options,  //the titles of buttons
                                            options[0]); //default button title
}
});

Upvotes: 0

Views: 5649

Answers (1)

msrd0
msrd0

Reputation: 8371

Your options must be sorted as the buttons will be without your custom options. In your case, this means that options[0] is mapped to JOptionPane.YES_OPTION and options[1] to JOptionPane.NO_OPTION.

For your code, you can use an if-statement like this:

if (n == JOptionPane.YES_OPTION) {
    // 5 point game
}
else if (n == JOptionPane.NO_OPTION) {
    // non stop game
}
else {
    // the user closed the dialog without clicking an button
}

See also this example.

Upvotes: 1

Related Questions