What's "inside" the TextField


Question

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
            }
        }
    }
});
1
1
5/2/2012 8:44:39 PM

Accepted Answer

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.

5
5/23/2017 10:30:08 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon