在 "JOptionPane.showInputDialog" 中,如果用户按下转义键或 X 按钮则显示错误(Java Swing)

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

我是 java 的新手,我只想在用户按下键盘上的 escape 键或单击 X 时显示一条错误消息按钮showInputDialog或按取消程序正常关闭,

就像现在,如果我关闭或取消 inputDialog,它会给出以下错误

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

我也尝试抛出异常 JVM 但它没有像我预期的那样工作,这是我的代码:

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

我只是想在用户单击 X 或取消提示时显示一条错误消息,我该如何捕获它?所以我会在那里实现我的逻辑

JOptionPane.showInputDialog returns null,而不是字符串,如果用户单击 'x' 或取消按钮。所以代替:

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

    case "1": ...

你会想做这样的事情:

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": ...

这将捕获 cancel/'x' 情况,continue 将使其跳到 while 循环的下一次迭代,而不是在它尝试使用带有 null 的 switch 语句时抛出错误。