2014-10-17 130 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 
}