Search code examples
javauser-interfacejtextfield

How do I catch the null value from my JtextField?


I have a JTExfield and if the user leaves the textfield empty I wanna catch it up and set the string to "NULL" It works if I write blablabla or whatever into the string and it should do but I also wanna catch if they leave it empty and put the text "NULL" into my file.

I have tried two solutions no one is working :

When user click ok button it performs this:

setPicture(pictureTextField.getText());

which is calling this method :

public void setPicture(String picture) {

            if (picture == null) {

                picture = "NULL";

            }

            this.picture = picture;
        }

and :

public void setPicture(String picture) {

        if (picture == "") {

            picture = "NULL";

        }

        this.picture = picture;
    }

So to repeat what I want to do is to set my picture String to "NULL" is the user leaves the textField empty.


Solution

  • Combine the null and empty checks together:

    public void setPicture(String picture) {
    
      if (picture == null || picture.isEmpty()) {
    
        picture = "NULL";
    
      }
    
      this.picture = picture;
    }