1

I have the following JavaFX code:

final TextField textField = new TextField();

and anEventHandler<ActionEvent>with checking textField wether it's empty or not. The problem is that textField.getText() == null or textField.getText() == "" both returns false, but i didn't print anything in that field, so it should return true.


final TextField textField = new TextField();
browse.setOnAction(new EventHandler() {
    @Override
    public void handle(ActionEvent actionEvent) {
        FileChooser fileChooser = new FileChooser();
        File chFile = fileChooser.showOpenDialog(stage);
        if (chFile != null) {
            // some code
            if (textField.getText() != null && textField.getText() != "") {
                // some code
            }
        }
    }
});
4lex1v
  • 21,367
  • 6
  • 52
  • 86

2 Answers2

5

The textField.getText() returns a java String. Java String is an Object so you should use equals() method instead of == to compare Strings. == operator is used for comparing primitive types in Java. To understand this better, please look this How do I compare strings in Java? Q/A for string comparison in Java.
As I said you can use textField.getText().equals("") for checking the String emptiness but the common usage for it is:

     if (textField.getText() != null && ! textField.getText().trim().isEmpty()) {
          // some code
     }

where ! is a boolean NOT operator. Also not the trim() method. This is for checking if the user entered whitespaces only then treat them as an empty value. Otherwise checking the whitespaces with equals("") will fail.

Community
  • 1
  • 1
Uluk Biy
  • 48,655
  • 13
  • 146
  • 153
-1
if(textfield.getText().trim().length>0)
//do Something
else
//can't be blank
x2.
  • 9,554
  • 6
  • 41
  • 62
sagar
  • 1