在Java中,getSource()方法用于获取事件源对象。它通常用于处理GUI事件,例如按钮点击事件、鼠标点击事件等。
以下是使用getSource()方法的示例代码:
import java.awt.*;import java.awt.event.*;public class EventExample {private Button button;public EventExample() {// 创建一个按钮对象button = new Button("Click me");// 添加按钮点击事件监听器button.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {// 获取事件源对象Object source = e.getSource();// 判断事件源是否为按钮对象if (source == button) {System.out.println("Button clicked");}}});// 创建一个窗口对象Frame frame = new Frame("Event Example");frame.add(button);frame.setSize(300, 200);frame.setVisible(true);}public static void main(String[] args) {new EventExample();}}在上面的示例代码中,我们创建了一个按钮对象,并为按钮添加了一个点击事件监听器。当按钮被点击时,actionPerformed()方法会被调用,并通过getSource()方法获取到按钮对象。然后我们可以根据事件源对象的类型进行相应的处理。

