So I need to simply check whether a clicked button's text is "X" or "O" (making tic tac toe)
This code doesn't work:
if (jButton1.getText()=="X")
However the following code does work:
String jButText = jButton1.getText();
if (jButText=="X")
Why doesn't the first bit of code work when the second does? Does it need to be something more like if (jButton1.getText().toString=="X")? By the way, I don't think toString exists in Java. That is just somewhat the equivalent in Visual Basic, which is what I normally use to create GUIs.
解决方案
This behavior is not reproducible in java 1.7.0_45 or 1.7.0_25, it might be a weird occurrence of String interning for your java version.
In order for your code to work properly on all java versions you have to use equals()
== compares objects meanwhile .equals() compares the content of the string objects.
jButton1.getText().equals("X")