2014-10-17 127 views
1

我正在用Java编写我的第一个复杂应用程序Swing。当我将ActionListener添加到我的JButton中时。java中的ActionListener对第二次点击执行操作

ActionListener changeButton = new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent e){ 
     if(startButton.getText() == "Spustit") { 
      startButton.setText("STOP"); 
     } else { 
      startButton.setText("Spustit"); 
     } 
    } 
} 

我加入ActionListener添加到按钮本身

private void startButtonActionPerformed(java.awt.event.ActionEvent evt) { 
    startButton.addActionListener(changeButton); 
} 

你能告诉我在哪儿编码的ActionListener不好?

谢谢大家!

+0

你调试过该方法是否被调用? – Smutje 2014-10-17 12:17:08

+0

@Smutje:好的,方法被调用,但不是第一次点击。它仅在第二次或第三次点击时“有效” – 2014-10-17 12:22:59

+1

你在哪里编码不好?例如这里:'startButton.getText()==“Spustit”'。将字符串与“equals”进行比较,而不是用“==”进行比较。虽然,由于使用了intented字符串,你的比较可能会奏效,但你应该修正它。 – Tom 2014-10-17 12:23:23

回答

3

您已经对ActionListener进行了编码,至少对于动作侦听器本身来说至少可以工作。问题在于你在一个事件(你的第二个示例)之后添加了动作监听器,因此你的动作监听器将在你第二次点击它时被调用。

一种解决方案是非常简单的:

JButton button = new JButton(); 
button.addActionListener(new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     //... 
    } 
}); 

现在的动作监听应激活第一个点击,如果你直接添加一个新的ActionListener添加到按钮,不执行一个操作之后

+0

非常感谢,这工作正常! – 2014-10-17 12:31:41

1

为什么你在actionPerformed中添加了actionlistener?我认为你应该这样做:

public static void main(String[] args) { 
    final JButton startButton = new JButton("Spustit"); 
    ActionListener changeButton = new ActionListener() { 
     @Override 
     public void actionPerformed(ActionEvent e) { 
      if (startButton.getText() == "Spustit") { 
       startButton.setText("STOP"); 
      } else { 
       startButton.setText("Spustit"); 
      } 
     } 
    }; 
    startButton.addActionListener(changeButton); 
    // Add it to your panel where you want int 
}