JCalander Combobox的空指针异常

时间:2013-04-06 14:03:32

标签: java date calendar datepicker

我的Java应用程序从JCalander Combobox生成空指针异常。我试图抓住错误。但那没有用。有人可以帮助我解决这个问题。请。

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.util.Calendar.setTime(Calendar.java:1106)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:955)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:948)
at java.text.DateFormat.format(DateFormat.java:336)
at org.freixas.jcalendar.JCalendarCombo.paramString(JCalendarCombo.java:780)
at java.awt.Component.toString(Component.java:8095)


 tbmodel = (DefaultTableModel)tblItmQty.getModel();
        System.out.println(calRecvDate.getDate());
        try{
        if(calRecvDate.getDate()==null){ // Error
            JOptionPane.showMessageDialog(null, "Please Select Shippment Received Date");  
            calRecvDate.requestFocus();

        }else if(txtShipSs.getText().isEmpty()){

/////////////////////////////////////////////// /////////////////

  if (inputValidate() == true) {

              try {
                    String shipId = txtShipId.getText();
                    String invID = txtInvoice.getText();
                    String shipSs = txtShipSs.getText();
                    String address = txtNtfAddress.getText();
                    String sipper = txtAShipper.getText();
                    String vessal = txtVessal.getText();
                    Date rcvDate = calRecvDate.getDate(); // Jcalander
                    String consignee = txtConsigne.getText();


                    ArrayList<ShippmentItems> shipItems = new ArrayList<ShippmentItems>();
                    tbmodel = (DefaultTableModel) tblItmQty.getModel();

                    for (int i = 0; i < tbmodel.getRowCount(); i++) {
                          String itmcode = (String) tbmodel.getValueAt(i, 0);
                          String itmName = (String) tbmodel.getValueAt(i, 1);
                          int qty = (int) tbmodel.getValueAt(i, 2);
                          ShippmentItems shpItems = new ShippmentItems(shipId, itmcode, itmName, qty);
                          shipItems.add(shpItems);
                    }

1 个答案:

答案 0 :(得分:1)

因为这会抛出NPE:

calRecvDate.getDate()==null

calRecvDate变量为null,您需要在使用之前检查它是否为null,或者通过在代码中追溯到您认为已初始化的位置来确保它不为null它并解决问题(因为它没有初始化)。

要检查它是否为空,您可以执行以下操作:

if (calRecvDate != null) {
  // use the calRecvDate variable here
} else {
  // initialize the calRecvDate variable here

  // or perhaps better, display a JOptionPane error message to the user
  // that the date hasn't been selected, and exit this method by calling return:

  return;
}

同样,不要使用try / catch块来处理NullPointerExceptions。