问题
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.
回答1:
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")
回答2:
This was also driving me nuts when using AWT Button class... Here's the answer: There is no .getText() method for a Button... you need to use .getLabel()
Now, the story for JButtons: Depending on your version of java, getLabel() was deprecated, and finally replaced by getText... Aren't namespaces wonderful?
回答3:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyFrame extends JFrame{
JButton equalsButton;
JLabel ansLabel;
JLabel addLabel;
JTextField text1;
JTextField text2;
MyFrame (){
setSize(300,300);
setDefaultCloseOperation(3);
setLayout(new FlowLayout());
text1=new JTextField(10);
add(text1);
addLabel=new JLabel("+");
add(addLabel);
text2=new JTextField(10);
add(text2);
equalsButton=new JButton("=");
equalsButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
int num1=Integer.parseInt(text1.getText());
int num2=Integer.parseInt(text2.getText());
int tot=num1+num2;
ansLabel.setText(Integer.toString(tot));
}
});
add(equalsButton);
ansLabel=new JLabel(" ");
add(ansLabel);
pack();
setVisible(true);
}
}
class Demo{
public static void main(String args[]){
MyFrame f1=new MyFrame();
}
}
回答4:
in java when you compare strings using == , you're comparing their memory addresses, to check if two strings contains same text you should call .equals()
if ("X".equals(jButton1.getText()))
来源:https://stackoverflow.com/questions/20082051/getting-text-value-from-a-jbutton