从JCalander组合框空指针异常(Null Pointer Exception from JCa

2019-10-17 23:18发布

我的Java应用程序产生空指针异常从JCalander组合框。 我试图捕获错误。 但是,没有工作。 有人可以帮助我解决这个问题。 请。

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);
                    }

Answer 1:

由于这将引发的NPE:

calRecvDate.getDate()==null

calRecvDate变量是空的,你要么需要检查它是否是空在使用它之前,或者确保它不是通过追溯您的代码中,你认为你已经初始化它和解决问题为空(因为它未初始化)。

要检查它是否为空,你可以这样做:

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的。



文章来源: Null Pointer Exception from JCalander Combobox