【问题标题】:I am getting a NullPointer exception in a java program我在 Java 程序中收到 NullPointer 异常
【发布时间】:2013-06-09 02:36:37
【问题描述】:

您好,我在运行程序时收到 Nullpointer 错误。我在这个网站上发现了一篇我认为可以解决问题的帖子Null Pointer Exception from JCalander Combobox 我使用了这个页面上的建议,但仍然收到错误消息。谁能告诉我哪里出错了?

    String end;
    if (jTimeButton3 != null) {
        SimpleDateFormat dateFormatTime2 = new SimpleDateFormat("hh:mm a");
        end = dateFormatTime2.format(jTimeButton3.getTargetDate());
        endTime.setText(end);
    } else {
        JOptionPane.showMessageDialog(
                null, "Please select a End Time.");

        return;
    }

【问题讨论】:

  • 请发布NullPointerException的stacktrace
  • 发布一个堆栈跟踪,并完成您的代码,好吗?
  • 如需更好的帮助,请尽快发帖SSCCE
  • 错误在此代码的第 4 行
  • @Reimeus 更像是 jTimeButton3.getTargetDate() 为空。他已经对 jTimeButton3 进行了空检查。

标签: java swing nullpointerexception simpledateformat


【解决方案1】:

您收到 NullPointerException 是因为您的 jTimeButton3.getTargetDate() 为 Null:

您可以通过测试您的日期来修复它:

String end;
if (jTimeButton3 != null && jTimeButton3.getTargetDate() != null) {
    SimpleDateFormat dateFormatTime2 = new SimpleDateFormat("hh:mm a");
    end = dateFormatTime2.format(jTimeButton3.getTargetDate());
    endTime.setText(end);
} else {
    JOptionPane.showMessageDialog(
            null, "Please select a End Time.");

    return;
}

【讨论】:

  • @Majid L 谢谢你的帮助。
【解决方案2】:

您的代码看起来不错,只是您应该检查 endTime 引用,它可能为 null 并且您正在调用 setText 。对其进行空指针检查以解决问题。

【讨论】:

    【解决方案3】:

    仔细查看您的代码可以发现几乎 100% 的候选者是 NPE:

    这是您的代码:

    String end;
        if (jTimeButton3 != null) {
            SimpleDateFormat dateFormatTime2 = new SimpleDateFormat("hh:mm a");
            end = dateFormatTime2.format(jTimeButton3.getTargetDate());
            endTime.setText(end);
        } else {
            JOptionPane.showMessageDialog(
                    null, "Please select a End Time.");
    
            return;
        }
    

    jTimeButton3 没有抛出 NPE,因为您正在检查 if 语句,dateFomatTime2 也是 != null,这意味着 endTime 是我们剩下的候选人,所以我建议您发布另一部分代码。

    注意:仅当您确定 NPE 在您发布的代码中时,此答案才有用

    【讨论】:

      猜你喜欢
      • 2010-10-15
      • 2017-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-21
      • 1970-01-01
      • 1970-01-01
      • 2018-08-25
      相关资源
      最近更新 更多