-2

I'm trying to us an if-else statement to check if they typed something specific in the TextField but it will never return true. How do I get this to work or is there a work around?

    String text = textField.getText();
    if(text == "work"){
        textArea.append("Text was " + text + newline);
        textArea.append("If you see this then it worked");
    }else{
        textArea.append(text + newline);
    }

This will display "work" for me.

For convenient purposeses I used the oracle tutorial to test this to see if my JTextField http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TextDemoProject/src/components/TextDemo.java

Spik330
  • 502
  • 4
  • 6
  • 19

1 Answers1

1

This is happening because you don't understand or missundertood how Strings work in Java. Strings are objects and usually you will need to compare them (their content) using the equals method. So, you need to use this in your if:

// equals will return true if the content of the text field is
// the same as the string used in the comparison, i.e., "work"
if ( text.equals( "work" ) ) {   
    // do something
}

Your code does not work because the String that is inside your text field is not the same object that the String "work" that you are using in your if. So, you need to compare their content, i.e., you need to verify if these two different String objects have the same value.

I recommend the following links:

http://docs.oracle.com/javase/tutorial/java/data/strings.html (you must read the entire String tutorial) http://javarevisited.blogspot.com.br/2013/07/java-string-tutorial-and-examples-beginners-programming.html this is not an official documentation, but it is ok. look specially the itens 3 and 4

davidbuzatto
  • 9,207
  • 1
  • 43
  • 50