Search code examples
javaswingjoptionpane

Find out Ok in JOptionPane InputDialog


This is my input dialog:

enter image description here

But my code can't recognize selected buttons correctly:

(No message appear on console at all)

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

Solution

  • The result of showInputDialog returns you the value you enter in the inputbox. So comparing it with ok or cancel option does not make sense.

    There goes your new code:

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