JOptionPane 取消按钮不能正常工作

JOptionPane cancel button doesn't work properly

我正在使用 JOptionPane。当用户点击 ok 按钮时效果很好,但是当点击 cancel 按钮以及关闭消息时,它会显示错误留言。

private void findActionPerformed(java.awt.event.ActionEvent evt) {                                     

    try {
        String num = JOptionPane.showInputDialog("Number to Search:");
        int number = Integer.parseInt(num);
        s.search(number);
   }catch (Exception e) {
        JOptionPane.showMessageDialog(this, "WRONG INPUT: you must insert integers", "Erorr", JOptionPane.ERROR_MESSAGE);
    } 
} 

使用

private void findActionPerformed(java.awt.event.ActionEvent evt) {                                     

    try {
        String num = JOptionPane.showInputDialog("Number to Search:");
        if(num != null)
        { 
            int number = Integer.parseInt(num);
            s.search(number);
        }
    }catch (Exception e) {
        JOptionPane.showMessageDialog(this, "WRONG INPUT: you must insert integers", "Erorr", JOptionPane.ERROR_MESSAGE);
    } 
} 

JOptionPane returns null 当关闭它或按取消时。因此,只需按照上面的代码所示进行检查即可。当您将 null 传递给 Integer.parseInt().

时将抛出异常