Null Pointer Exception from JCalander Combobox

2019-08-02 12:39发布

问题:

My Java Application produces Null Pointer Exception from JCalander Combobox. I tried to catch the error. But that didnt work. Can someone assist me to fix this. Please.

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:

Since this throws the NPE:

calRecvDate.getDate()==null

The calRecvDate variable is null, and you will either need to check if it's null before using it, or make sure that it isn't null by tracing back in your code to where you think you've initialized it and fix the problem (since it isn't initialized).

To check if it's null, you could do:

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

Again, don't use try/catch blocks to handle NullPointerExceptions.