首页 > 解决方案 > 在 JOptionPane.ShowInputDialog 中验证用户输入

问题描述

使用 JOptionPane.ShowInputDialog,我需要检查用户是否输入了 int,否则,JOptionPane 应该返回错误消息并提示用户输入正确的数据类型。

同时,如果用户点击取消程序应该返回主菜单。

String weight = JOptionPane.showInputDialog(null, "Enter your weight in Kg: ");
if(weight == null) {
    menuGUI();
} else {
    setWeight(Integer.valueOf(weight));
}

关于我如何做到这一点的任何建议?

标签: javauser-interfacejoptionpane

解决方案


使用 while 循环

Integer w = null;
while (true) {
    String weight = JOptionPane.showInputDialog(null, "Enter your weight in Kg: ");
    if (weight == null) {
        break;
    }

    try {
        w = Integer.parseInt(weight);
        break;
    } catch (NumberFormatException e) { 
        JOptionPane.showMessageDialog(null, "Enter a valid integer", "error", JOptionPane.ERROR_MESSAGE);
    }
}

if (w == null) { //The user clicked cancel
    menuGUI();
} else { //Do what you want with w
}

推荐阅读