【问题标题】:In "JOptionPane.showInputDialog" show error if user press escape or X button (Java Swing)如果用户按下转义或 X 按钮(Java Swing),则在“JOptionPane.showInputDialog”中显示错误
【发布时间】:2018-09-03 18:02:04
【问题描述】:

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

就像现在如果我关闭或取消 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 或取消提示,我只想显示一条错误消息,我怎样才能捕捉到这个?所以我会在那里实现我的逻辑

【问题讨论】:

  • 问题出在第 11 行。我们不知道第 11 行是哪个语句。在您的代码中找到第 11 行并确定该行中的哪个变量为空,然后解决问题。
  • 我只想在用户单击 X 或取消提示时显示错误消息,我该如何捕捉?所以我会在那里实现我的逻辑

标签: java swing joptionpane swingx


【解决方案1】:

如果用户单击“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 语句时抛出错误。

【讨论】:

    猜你喜欢
    • 2021-12-08
    • 2012-12-09
    • 2012-10-10
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    相关资源
    最近更新 更多