这是我的输入对话框:
但我的代码无法正确识别所选按钮:
(根本没有消息出现在控制台上)
public static void main(String[] args) {
int userId = Integer.parseInt(JOptionPane.showInputDialog("Enter User ID", "").trim());
if (userId == JOptionPane.OK_OPTION) {
System.out.println("ok selected");
} else if (userId == JOptionPane.CANCEL_OPTION) {
System.out.println("Cancel selected");
}
}
}
答案 0 :(得分:2)
showInputDialog的结果返回您在输入框中输入的值。因此将它与ok或cancel选项进行比较是没有意义的。
你的新代码:
public static void main(String[] args) {
String result = JOptionPane.showInputDialog("Enter User ID", "");
if(result == null) {
System.out.println("cancel selected");
return;
}
int userId = Integer.parseInt(result.trim());
System.out.println("user id is:" + userId );
}