我有一個帶2個JButton的GUI,我想通過使用getSource方法知道哪一個正在觸發一個事件。我找遍了整個谷歌爲解決我的問題,但無法找到一個,這裏是我的代碼:在按鈕上使用getSource方法遇到問題
@Override
public void actionPerformed(ActionEvent event){
if (event.getSource() == btn1){
System.out.println("this should work");
}else if (event.getSource() == btn2){
System.out.println("this should work as well");
}
但是當我按下其中一個按鈕未打印任何東西,我也試過這樣:
@Override
public void actionPerformed(ActionEvent event){
if ((JButton)event.getSource() == btn1){
System.out.println("this should work");
}else if ((JButton)event.getSource() == btn2){
System.out.println("this should work as well");
}
但這也沒有工作。
有人可以告訴我什麼是錯?
我不知道在這種情況下它是否有所不同,但是,您是否嘗試過'equals()'而不是'=='? – acdcjunior
嘗試System.out.println(event.getSource)來檢查源是什麼 – BlackJoker
設置斷點並手動檢查event.getSource()返回的值。 –