从jButton获取文本值

所以我需要简单地检查点击按钮的文本是"X"还是"O" (制作tic tac toe)此代码不起作用:

 if (jButton1.getText()=="X") 

但是,以下代码确实有效:

 String jButText = jButton1.getText(); if (jButText=="X") 

为什么第二个代码不能在第二个代码工作时起作用? 是否需要更像if( jButton1.getText().toString=="X" )? 顺便说一句,我不认为toString存在于Java中。 这在Visual Basic中有点相同,这是我通常用来创建GUI的东西。

此行为在java 1.7.0_45或1.7.0_25中不可重现,对于您的Java版本,它可能是奇怪的String interning 。

为了让您的代码在所有Java版本上正常工作,您必须使用equals()

==同时比较对象.equals()比较字符串对象的内容。

 jButton1.getText().equals("X") 

当使用AWT Button类时,这也让我感到疯狂……这就是答案:Button没有.getText()方法……你需要使用.getLabel()

现在,JButtons的故事:根据你的java版本,不推荐使用getLabel(),最后用getText代替……不是命名空间很棒吗?

 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(); } } 

在java中使用==比较字符串时,你要比较它们的内存地址,检查两个字符串是否包含你应该调用的相同文本.equals()

 if ("X".equals(jButton1.getText()))