我有一些问题,我只是从jCalendar中的jDateChooser获取空值。

此方法用于将java.util.Date转换为XMlGregorianCalendar的功能:

DatatypeFactory df;
public XMLGregorianCalendar function_ConvertAsXMLGregorianCalendar(Date date) {
    if (date == null) {
        System.out.println("Error on Function Convert Date into XML Gregorian Calendar");
        return null;
    } else {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTimeInMillis(date.getTime());
        return df.newXMLGregorianCalendar(gc);
    }
}


这是getStart和getEnd Dates的2个函数。

private XMLGregorianCalendar getStartDate(){
    Date dateStarting  = jDateChooserStart.getDate();
    System.out.println("Date Start : " + dateStarting.toString());
    XMLGregorianCalendar cal = function_ConvertAsXMLGregorianCalendar(dateStarting);
    System.out.println("Converted Date : " + cal.toXMLFormat());
    return cal;
}

private XMLGregorianCalendar getEndDate(){
    Date dateEnding = jDateChooserEnd.getDate();
    System.out.println("Date End : " + dateEnding);
    return function_ConvertAsXMLGregorianCalendar(dateEnding);
}


然后,我将方法放在称为schedule的对象中:

schedule.setStartDate(getStartDate());
schedule.setEndDate(getEndDate());


Netbeans(v7.1)的结果

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Frames.CreateSchedule.function_ConvertAsXMLGregorianCalendar(CreateSchedule.java:181)
at Frames.CreateSchedule.getStartDate(CreateSchedule.java:188)
at Frames.CreateSchedule.SubmitButtonActionPerformed(CreateSchedule.java:204)
at Frames.CreateSchedule.access$000(CreateSchedule.java:16)


怎么了?

之前谢谢。

更新::

我只是将函数更改为此:

public XMLGregorianCalendar function_ConvertAsXMLGregorianCalendar(Date date) {
    if (date == null) {
        System.out.println("Error on Function Convert Date into XML Gregorian Calendar");
        return null;
    } else {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTimeInMillis(date.getTime());
        DatatypeFactory df = null;
        return df.newXMLGregorianCalendar(gc);
    }
}


更新2#::

初始化newInstance()方法后,出现另一个错误:

java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date


我只是从更改包名称

java.util.Date into java.SQL.Date


然后投射:

Date dateStarting  = (Date) jDateChooserStart.getDate();
Date dateEnding    = (Date) jDateChooserEnd.getDate();


如何解决这个问题?

再次感谢。

最佳答案

似乎已声明但未实例化df

DatatypeFactory df;


从这里:

df.newXMLGregorianCalendar(gc);
^


您可以使用DatatypeFactory.newInstance()首先实例化,如下所示:

DatatypeFactory df = DatatypeFactory.newInstance();

07-24 14:57