0

I wrote this little piece of code in JavaFX:

tfb.setOnAction(new EventHandler<ActionEvent>() {
    @Override public void handle (ActionEvent e) {
        if(tf1.getText() == "test") {
            System.out.println("correct");
        } else {
            System.out.println("wrong");
        }
    }
});

When I enter "test" in the text field, I always get a "wrong" printed by my code, not a "correct" as it should be. I checked several times whether I spelled "test" correctly, and I also tried to put "test" in quotation marks (double: " and single: '), none of this helped.

I already tried to print out the content of the text field (with System.out.Println(tf1.getText())), and I got what I wrote in the text field on the console, so the action listener and tf1.getText() work for sure.

What can be wrong with my code?

mustaccio
  • 18,234
  • 16
  • 48
  • 57
  • 1
    BTW: `'`-quotes are for chars only. The compiler only allows you to add exactly one char in between those. – fabian Jun 12 '19 at 14:47

1 Answers1

-1

try to replace the if with the following,

if(tf1.getText().toString().equalsIgnoreCase("test")){
     System.out.println("correct");
} else {
     System.out.println("wrong");
}
Akshatha S R
  • 1,237
  • 1
  • 15
  • 30
  • 2
    `TextField.getText` returns a string and the question does not indicate that case of letters should be ignored... – fabian Jun 12 '19 at 14:48
  • For string comparison you should use .equals or equalsIgnoreCase instead of '==', better use equalsIgnoreCase if it is not case sensitive – Akshatha S R Jun 13 '19 at 04:19