Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: check if datepicker has value error

I have a

DatePicker date = new DatePicker();
date.setValue(LocalDate.now());

The field is still manually editable, so you can just remove the initial set value.

I have a button with which I want to check if the DatePicker value is empty. But when I do if(date.getValue().equals(null), I get a java.lang.NullPointerException:

Button btn = new Button();
btn.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent evt) {
         if(date.getValue().equals(null) {
            // do something
         }
     }
   });

How can I properly check if the value is empty?

like image 762
sandboxj Avatar asked Oct 17 '25 18:10

sandboxj


2 Answers

if (date.getValue().equals(null) { ... }

If the value is really a null, you'll get a NullPointerException exception. So, you'd better write like:

if (date.getValue() == null) { ... }

Keep in mind, if you use equals, you should be sure that the left part of an expression (an instance this method is called on) never presents a null (like constants, String literals, enums do).


Also, you are free to replace an anonymous class with a lambda for conciseness:

btn.setOnAction(event -> { ... });

Furthermore, there's a good one-line way to set a default value if the current is a null (to LocalDate.now(), for example):

datePicker.setValue(Optional.ofNullable(datePicker.getValue()).orElse(LocalDate.now()));
like image 137
Andrew Tobilko Avatar answered Oct 21 '25 23:10

Andrew Tobilko


You can't call methods on a null reference. As you've seen, that would produce a NullPointerException. Instead, you should use the == operator to check that the reference is [not] null:

if (date.getValue() == null) {
    // Here --------^
like image 40
Mureinik Avatar answered Oct 21 '25 23:10

Mureinik