我在java程序中得到一个NullPointer异常

时间:2013-06-09 02:36:38

标签: java swing nullpointerexception simpledateformat

嗨我运行程序时遇到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;
    }

3 个答案:

答案 0 :(得分:3)

您收到NullPointerException,因为jTimeButton3.getTargetDate()为空:

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

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

答案 1 :(得分:0)

您的代码看起来不错,除了您应该检查endTime引用,它可能为null并且您正在调用setText。在它周围放一个空指针来解决问题。

答案 2 :(得分:0)

仔细查看您的代码,可以看出几乎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位于您要发布的代码段中时,此答案才有用