1

我的 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);
                    }
4

1 回答 1

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。

于 2013-04-06T14:18:48.313 回答