String k1 =f.getText(); //f是JTestField的引用。
f.getText().equals("呵呵");//呵呵是字符串,如果这样写的话返回是真。
但是如果写成k1.equals("呵呵");返回的就是假,这是为什么?求解释。
补充:
package tao ;
import java.awt.* ;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Tao{
static JTextField f = new JTextField();
static JPasswordField f1 = new JPasswordField();
public static void main(String[] args){
JFrame chat = new JFrame();
chat.setSize(300,200);
//小部件;
JButton log = new JButton("呵呵");
JButton log1 = new JButton("嘻嘻");
JButton log2 = new JButton("吼吼");
JLabel l = new JLabel("账号是什么");
JLabel l2 = new JLabel("密码又是什么");
Monitor mo = new Monitor();
log.addActionListener(mo);
//小模块;
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(2,2));
p1.add(l);
p1.add(f);
p1.add(l2);
p1.add(f1);
JPanel p2 = new JPanel();
p2.add(log);
p2.add(log1);
p2.add(log2);
//整合模块;
chat.setLayout(new GridLayout(2,1));
chat.add(p1);
chat.add(p2);
chat.setVisible(true);
}
static class Monitor implements ActionListener{
String k1 =f.getText();
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("呵呵")){
if(f.getText().equals("GEM")&&(String.valueOf(f1.getPassword()).equals("111111"))){
System.exit(0);
}
}
}
}
}
以上是代码,想实现的效果是输入两个制定的账号密码以后按呵呵会关闭,但是如果换成String的引用.equals就不能关闭了。谢谢!