【问题标题】:How can I handle my Input dialog correctly?如何正确处理我的输入对话框?
【发布时间】:2016-12-26 07:41:54
【问题描述】:

输入对话框将显示项目的当前库存。我希望用户通过整数输入项目的新馆藏。

如果用户关闭或取消输入对话框,而输入文本字段中也没有任何内容,我想返回主菜单。即使用户在输入文本字段中有内容也会发生这种情况。

如果用户输入一个字符串,将捕获一个数字格式异常,并提示用户只输入一个数字。

如果输入为空,并且用户单击“确定”,将显示一个消息对话框并告诉用户您需要输入一个数字。

目前,我发现在我的输入对话框中实现这些方法非常困难。

这是我的代码:

int newInput = Integer.parseInt(JOptionPane.showInputDialog(null, "Your current holdings are: "
            + currentHoldings, "Edit Holdings", JOptionPane.CANCEL_OPTION));

                    //Currently, when closing the program if newInput is empty
                    //It goes straight to the number format exception
                    //I need the program closed if the user closes it.
                    if (newInput == JOptionPane.CLOSED_OPTION)
                    {
                        JOptionPane.getRootFrame().dispose();
                        break;
                    }

                    ...

                    catch (NumberFormatException nfe)
                    {
                        JOptionPane.showMessageDialog(null, "Please enter in a number!");
                    }

即使文本字段为空并且用户通过红叉或取消按钮关闭,仍然会抛出数字格式异常。即使文本字段中没有任何内容,我也希望程序关闭。

如何检查用户是否在输入对话框文本字段中输入了任何内容?我目前也发现很难实现此功能。

我的问题是,如果用户输入为空或关闭输入对话框,如何更好地管理输入对话框以处理退出按钮。

感谢您的帮助。

【问题讨论】:

  • 为什么要将对话结果与JOptionPane.CLOSED_OPTION 进行比较?您还可以检查字符串是否是一个数字,而无需像 in 那样对其进行解析,从而绕过有问题的NumberFormatException。见stackoverflow.com/questions/1102891/…
  • 如果用户单击关闭按钮,我不确定如何处理。我到处寻找,无法找到解决方案。不过,我会检查整数处理的解决方案,谢谢。我也有两个 JOptionPanes 正在运行,我只想关闭当时打开的那个。

标签: java input dialog modal-dialog joptionpane


【解决方案1】:

你可以这样做:

String code = JOptionPane.showInputDialog(null, "Your current holdings are: "
            + currentHoldings, "Edit Holdings", JOptionPane.CANCEL_OPTION);

    if (code == null){ //cancel button or "x" button

    }
    else if ("".equals(code)){ //don't input anything and click ok

    }
    else {
        //parse code to int and do what you want

    }

【讨论】:

  • 当我关闭输入对话框时仍然抛出空指针异常。
  • 关闭输入对话框时,会转到第一个if
猜你喜欢
  • 2011-02-13
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-01
  • 1970-01-01
  • 2020-01-17
  • 1970-01-01
相关资源
最近更新 更多