在JOptionPane InputDialog中找到确定

时间:2014-09-12 18:19:14

标签: java swing joptionpane

这是我的输入对话框:

enter image description here

但我的代码无法正确识别所选按钮:

(根本没有消息出现在控制台上)

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");
    }
  }
}

1 个答案:

答案 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 );


}