Reputation: 43
Hi I am getting a Nullpointer error when I run my program. I found a post on this site that I thought would fix the problem Null Pointer Exception from JCalander Combobox I used the suggestions from this page but am still getting the error. Could someone please tell me where I went wrong?
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;
}
Upvotes: 1
Views: 172
Reputation: 7742
Taking a good look at your code reveals the almost 100 percent candidate for being NPE:
Here is your code:
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 is not throwing NPE since you are checking in the if
statement, dateFomatTime2
is != null too, meaning that endTime
is our candidate left, so I'll advice you to post the other part of the code.
Note: This answer is useful only if you are certain that the NPE is in the piece of code you are posting
Upvotes: 0
Reputation: 19788
You are getting a NullPointerException because your jTimeButton3.getTargetDate()
is Null:
You can fix it by testing your date:
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;
}
Upvotes: 3
Reputation: 68715
Your code looks good except that you should put a check for your endTime reference, it may be null and you are calling setText on it. Put a null pointer check around it to nail the problem.
Upvotes: 0