Reputation: 33
I am trying to make a game for a project and I need help. I created a dialog box where the user is presented with two options. They can chose to "Use the car" or they can chose to "walk". How do I code further so that after they chose an option, something happens. For example, if they chose "Use the car" it will return "good choice" whereas if they chose "walk" it will return "bad choice".
public void travel ()
{
Object [] options = { "Use the car", "Walk" };
JOptionPane.showOptionDialog(null, //Component parentComponent
"How do you want to get to Jim's?", //Object message,
"Transportation Method", //String title
JOptionPane.YES_NO_OPTION, //int optionType
JOptionPane.INFORMATION_MESSAGE, //int messageType
null, options, options [0]); //Icon icon,
if(options == 0 ){
System.out.println ("Test Option 1");//Use car was chosen
}else{
System.out.println ("Test Option 2");//Walk was chosen
}
}
This is my code so far but I receive an error message "Error: incomparable types: java.lang.Object[] and int".
I would really appreciate your help. Thanks in advance
Upvotes: 0
Views: 1400
Reputation: 18569
JOptionPane.showOptionDialog return an integer indicating the option chosen by the user, or CLOSED_OPTION if the user closed the dialog.
So you need to store the result from showOptionDialog
int result = JOptionPane.showOptionDialog(null, //Component parentComponent
"How do you want to get to Jim's?", //Object message,
"Transportation Method", //String title
JOptionPane.YES_NO_OPTION, //int optionType
JOptionPane.INFORMATION_MESSAGE, //int messageType
null, options, options [0]); //Icon icon,
if(result == 0) System.out.println ("Test Option 1");
else System.out.println ("Test Option 2");
Upvotes: 3
Reputation: 347184
JOptionPane.showOptionDialog
will return "an integer indicating the option chosen by the user, or CLOSED_OPTION if the user closed the dialog"
You need to assign the return value and use it...
int result = JOptionPane.showOptionDialog(...);
if (result == 0) {
} else if (...
See How to Make Dialogs for more details
Upvotes: 4