如何将 if 语句添加到 JOptionPane

How to add if statements to JOptionPane

我正在尝试为一个项目制作游戏,我需要帮助。我创建了一个对话框,用户可以在其中看到两个选项。他们可以选择"Use the car",也可以选择"walk"。我该如何进一步编码,以便在他们选择一个选项后,会发生一些事情。例如,如果他们选择 "Use the car" 它将 return "good choice" 而如果他们选择 "walk" 它将 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
}
}

到目前为止,这是我的代码,但我收到一条错误消息 "Error: incomparable types: java.lang.Object[] and int"。

非常感谢您的帮助。提前致谢

JOptionPane.showOptionDialog 将 return "an integer indicating the option chosen by the user, or CLOSED_OPTION if the user closed the dialog"

您需要分配 return 值并使用它...

int result = JOptionPane.showOptionDialog(...);
if (result == 0) {
} else if (...

有关详细信息,请参阅 How to Make Dialogs

JOptionPane.showOptionDialog return 表示用户选择的选项的整数,或者 CLOSED_OPTION 如果用户关闭了对话框。

因此您需要存储 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");