按钮事件的字符串比较

时间:2011-01-14 19:03:25

标签: java swing

我有一个名为updatedDisplay的String,它在构造函数中设置为空。 按钮[]是JButtons,alarmCode是String字段。

我希望用户按下四个按钮(它们应该连接并存储在updatedDisplay字段中)。

执行checkCode()方法以尝试将updatedDisplay与alarmCode匹配。麻烦的是,他们从不匹配。我认为当我最初声明我的updatedDisplay时,它可能与“空间”有关,如下所示:

private String updatedDisplay =“”;

updatedDisplay字段似乎没有存储e.getActionCommand()值。

//add actionListeners to each button (except the "clear" button) to display value on screen
for (int i = 0; i< (buttons.length -1); i++) {
  buttons[i].addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e)
          {
          //store the name of the button in a local variable
          String command = e.getActionCommand();

          System.out.println("You clicked " + command);

          updatedDisplay = updatedDisplay + command;
          //updatedDisplay = command;
          System.out.println (updatedDisplay);

          screen.setText(updatedDisplay);
}
     });}

我有一个armButton,当按下时,应该触发checkCode()方法。该方法检查updatedDisplay和alarmCode是否相等:

//add actionListener to the arm button
armButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) 
        {
         checkCode(); 
        }
    });

注册码():

public void checkCode() {
//check if user entered the correct code
if (updatedDisplay == alarmCode)
{
  updatedDisplay =  "System Armed!";
  screen.setText(updatedDisplay);
}
else
{
  updatedDisplay  = "Incorrect Code, Try again!";
  screen.setText(updatedDisplay);
}
}

即使我按下按钮按下终端窗口,它们看起来也是正确的 - 但正如我所说,我怀疑在开始时输入了“空格”。

有什么想法吗?

1 个答案:

答案 0 :(得分:5)

解决方案

尝试:

if( updatedDisplay.equals( alarmCode ) { // ...

比较

要理解这一点,请阅读:

http://leepoint.net/notes-java/data/expressions/22compareobjects.html

摘要

由于updatedDatealarmCode是对象引用,因此您必须要求对象比较它们的值。您可以将它们视为指针,其值是内存中包含字符串的位置。您需要比较从该内存位置开始的文本,而不是比较指针(引用)的值。