JavaSwing输入对话框,点击取消抛出异常的解决方法

在做产品管理系统的时候,遇到一个问题:

  在得到一个输入框对话框的时候 String textPrice = JOptionPane.showInputDialog("请输入要调整的价格增(减)量");

         

  如果此时点击取消,则会抛出异常:java.lang.NullPointerException。

原因:点击取消不会产生String对象。

解决方法:

 1                 double price = 0;
 2                 String textPrice = JOptionPane
 3                         .showInputDialog("请输入要调整的价格增(减)量");
 4 
 5                 if (textPrice == null) {
 6                     return;
 7                 }
 8                 else if(textPrice.equals("")){
 9                     JOptionPane.showMessageDialog(null, "请输入要调整的价格增(减)量","提示信息",JOptionPane.ERROR_MESSAGE);
10                     return ;
11                 }
12                 else{
13                     try {
14                         price = Double.parseDouble(textPrice);
15                         if (pid.changePrice(price)) {
16                             JOptionPane.showMessageDialog(null, "价格调整完成!");
17                         }
18                     } catch (Exception e1) {
19                         JOptionPane.showMessageDialog(null, "输入有误!");
20                     }
21 
22                 }
23             }
View Code

 

posted @ 2015-01-16 16:15  N_ll  阅读(1109)  评论(0编辑  收藏  举报