【问题标题】:How to assign a sepecifc action to the ("Cancel") button within (JOptionPane.showInputDialog) in Java?如何在 Java 中为 (JOptionPane.showInputDialog) 中的 ("Cancel") 按钮分配特定操作?
【发布时间】:2011-09-07 15:37:19
【问题描述】:

这是我的一个简短示例代码的问题:

 double num = 0.00;

try
{
    num = Double.parseDouble(JOptionPane.showInputDialog("Enter your num:"));

}

catch (Exception e)
{
    System.err.println("Error: Invalid Input!");
    JOptionPane.showMessageDialog(null, "Error: Invalid Input!",  
    "Error", JOptionPane.ERROR_MESSAGE);
}

//Validate the num

if (num > 0.0 && num <= 1000.00)
{
    functionA();
}

else if (deposit <= 0.0 || deposit > 1000.00)
{
 System.err.println("Error: out of range");
}

*上面代码的问题是,当我点击“取消”按钮时,程序同时遇到两个错误:(超出范围和无效输入)。

请任何建议我如何解决这个问题?

提前致谢

【问题讨论】:

    标签: java swing actionlistener joptionpane


    【解决方案1】:

    首先,您需要验证输入是否为空。如果没有,那么你使用 parseDouble 就可以了。

    像这样:

    try
    {
        String i = JOptionPane.showInputDialog("Enter your num:");
        if (i != null)
            num = Double.parseDouble(i);
    }
    

    另外,尽量不要通过输入“异常”来捕获异常,就像你做的那样。始终尝试尽可能多地指定您正在寻找的异常。 在这种情况下,您应该使用 NumberFormatException 而不仅仅是 Exception。

    catch (NumberFormatException e)
    {
        System.err.println("Error: Invalid Input!");
        JOptionPane.showMessageDialog(null, "Error: Invalid Input!",  
        "Error", JOptionPane.ERROR_MESSAGE);
    }
    

    【讨论】:

    • 虽然这些建议解决了用户点击取消的问题,但它们并没有解决用户因按下取消或捕获数字格式异常而获得超出范围的升温的问题。我可以建议将验证代码移到 try 块中的 if 语句中。
    【解决方案2】:
    package org.life.java.so.questions;
    
    import java.text.ParseException;
    import javax.swing.JOptionPane;
    
    /**
     *
     * @author Jigar
     */
    public class InputDialog {
    
        public static void main(String[] args) throws ParseException {
            String input = JOptionPane.showInputDialog("Enter Input:");
            if(input == null){
                System.out.println("Calcel presed");
            }else{
                System.out.println("OK presed");
            }
    
    
        }
    }
    

    【讨论】:

    • 我喜欢看完整的代码示例。你的特别好。但是我可以提出“公民的要求”吗?删除多余的行。顶部的 4 在 IDE 之外是无意义的。第二条评论的第二行没有添加任何内容。 main 末尾的 2 个空白行也没有任何价值。删除这些行会缩短 E.G.从 26 行到仅 19 行 - 垂直节省约 25%。这可能与使用大显示器的人无关,但对于我们使用分辨率较小的旧显示器来说,在单个屏幕中更容易看到整个示例。感谢您考虑。
    • @Andrew Thompson 考虑 :)
    猜你喜欢
    • 1970-01-01
    • 2016-01-24
    • 2023-03-31
    • 2017-11-04
    • 1970-01-01
    • 2013-01-02
    • 2022-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多