共計 646 個字符,預(yù)計需要花費 2 分鐘才能閱讀完成。
在 Java 中,getSource()
函數(shù)是用于獲取事件源對象的方法,常用于事件處理程序中。
以下是使用 getSource()
函數(shù)的示例代碼:
import java.awt.*;
import java.awt.event.*;
public class MyFrame extends Frame implements ActionListener {private Button button;
public MyFrame() {button = new Button("Click me");
button.addActionListener(this);
add(button);
setSize(300, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {if (e.getSource() == button) {System.out.println("Button clicked");
}
}
public static void main(String[] args) {new MyFrame();}
}
在上面的示例中,button
是一個按鈕對象,我們通過調(diào)用 addActionListener()
方法為按鈕添加一個動作事件監(jiān)聽器,這個監(jiān)聽器是當前類 MyFrame
的實例。在 actionPerformed()
方法中,我們使用 getSource()
方法來獲取觸發(fā)事件的對象,然后判斷是否是按鈕對象,如果是,則打印 "Button clicked"。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完