Search code examples
javaswingjoptionpaneswingx

In "JOptionPane.showInputDialog" show error if user press escape or X button (Java Swing)


i am new to java, i just want to show an error message if user hit escape key from the keyboard or click on X button of showInputDialog or press cancel the program closes normally,

like now if i close or cancels the inputDialog it gives following error

Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:11)

i also tried to throw exception JVM but it does not works as i expected, here is my code:

String userInput;
BankAccount myAccount = new BankAccount();

while (true){
   userInput = JOptionPane.showInputDialog("1. Withdraw\n2. Deposit\n3. View Balance\n4. Exit");
    switch (userInput){

        case "1":
            myAccount.withdraw(Integer.parseInt(JOptionPane.showInputDialog("Please Enter ID: ")),Double.parseDouble(JOptionPane.showInputDialog("Please Enter Amount to Withdraw: ")));
            break;
        case "2":
            myAccount.deposit(Integer.parseInt(JOptionPane.showInputDialog("Please Enter ID: ")),Double.parseDouble(JOptionPane.showInputDialog("Please enter Amount to Deposit: ")));
            break;
        case "3":
            myAccount.viewBalance(Integer.parseInt(JOptionPane.showInputDialog("Please Enter ID: ")));
            break;
        case "4":
            myAccount.exit();
            System.exit(0);
        default:
            JOptionPane.showMessageDialog(null,"Invalid Input\nPlease Try Again");
            break;
    }
}

i just want to show an error message if user click X or cancels the prompt, how can i catch this? so i'll implement my logic there


Solution

  • JOptionPane.showInputDialog returns null, instead of a string, if the user clicks the 'x' or the Cancel button. So instead of:

    while (true){
      userInput = JOptionPane.showInputDialog("1. Withdraw\n2. Deposit\n3. View Balance\n4. Exit");
      switch (userInput){
    
        case "1": ...
    

    You would want to do something like:

    while (true){
      userInput = JOptionPane.showInputDialog("1. Withdraw\n2. Deposit\n3. View Balance\n4. Exit");
      if (userInput == null) {
        JOptionPane.showMessageDialog(null, "Invalid Input\nPlease Try Again", "Cannot Cancel", JOptionPane.ERROR_MESSAGE);
        continue;
      }
      switch (userInput){
    
        case "1": ...
    

    This will catch the cancel/'x' case, and the continue will have it skip to the next iteration of the while loop rather than throwing an error when it tries to use a switch statement with null.