在“JOptionPane.showInputDialog”中显示错误,如果用户按下escape或X按钮(Java Swing)

问题描述 投票:0回答:1

我是java新手,我只是想显示一条错误消息,如果用户从键盘点击转义键或点击showInputDialog的X按钮或按取消,程序正常关闭,

就像现在如果我关闭或取消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或取消提示时显示错误消息,我该如何捕获?所以我会在那里实现我的逻辑

java swing joptionpane swingx
1个回答
0
投票

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

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语句时抛出错误。

© www.soinside.com 2019 - 2024. All rights reserved.