我如何处理空的jXDatePicker?

时间:2014-04-17 19:22:33

标签: java swingx

我有一个包含jXDatePicker的摇摆表单来捕捉日期。如果未在jXDatePicker中选择日期,则在尝试将日期插入数据库时​​会引发错误。以下是我在Netbeans中遇到的错误:  线程“AWT-EventQueue-0”中的异常java.lang.NullPointerException。 下面是给我错误的代码:

    String dateOpened, dateOfLastUpdate, dateOf1stDelinquency, dateOfLastPayment,  dateClosed;
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    dateOpened = format.format(jXDatePicker7.getDate());
    dateOfLastUpdate = format.format(jXDatePicker2.getDate());
    dateOf1stDelinquency = format.format(jXDatePicker4.getDate());
    dateOfLastPayment = format.format(jXDatePicker5.getDate());
    dateClosed = format.format(jXDatePicker6.getDate());

String query2 = "insert into ACCOUNT (ACCOUNT_NUMBER,DATE_CLOSED ,DELINQUENCY_DATE,     UPDATE_DATE,AMOUNT_OWING,"
                + "BALANCE,PAYMENT_HISTORY,ACCOUNT_STATUS,MONTHLY_PAYMENT,TERMS_DURATION,PRINCIPAL,CREDIT_LIMIT,"
                + "DATE_OPENED,PORTIFOLIO_TYPE,ACCOUNT_TYPE,NATIONAL_ID,COSIGNER_NATIONAL_ID)"
                + "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        PreparedStatement preparedStatement2 = con.prepareStatement(query2);
        preparedStatement2.setString(1, acc_no);
        preparedStatement2.setString(2, dateClosed);
        preparedStatement2.setString(3, dateOf1stDelinquency);
        preparedStatement2.setString(4, dateOfLastUpdate);
        preparedStatement2.setDouble(5, amount_owing);
        preparedStatement2.setDouble(6, current_balance);
        preparedStatement2.setString(7, payment_history);
        preparedStatement2.setString(8, account_status);
        preparedStatement2.setDouble(9, monthly_payment);
        preparedStatement2.setDouble(10, terms_duration);
        preparedStatement2.setDouble(11, principal);
        preparedStatement2.setDouble(12, credit_limit);
        preparedStatement2.setString(13, dateOpened);
        preparedStatement2.setString(14, portfolio_type);
        preparedStatement2.setString(15, acc_type);
        preparedStatement2.setString(16, national_id);
        preparedStatement2.setString(17, cosigner_national_id);
        preparedStatement2.executeUpdate();

某些日期不是必需的且适用于某些情况,因此用户无法在这种情况下选择日期。

2 个答案:

答案 0 :(得分:1)

检查每个JXDatePicker的日期,如jXDatePicker2.getDate()为null。如果该日期恰好为null,则不要调用format.format。如果日期为空并且按下了enter,我会在format.format行中得到完全相同的错误。相反,请去一些默认时间,例如new Date(0);含义:

format.format(new Date(0));

答案 1 :(得分:0)

使用以下代码并确保数据库中的dateOpened列接受NULL值。

DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
if(jXDatePicker7.getDate() != null){
      dateOpened = format.format(jXDatePicker7.getDate());
}else{
   dateOpened = null;
}

如果您不想插入NULL值,请将错误消息显示为

 DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
 if(jXDatePicker7.getDate() != null){
       dateOpened = format.format(jXDatePicker7.getDate());
 }else{
    //error
 }