在 Java 里,“Event 事件”通常出现在 AWT / Swing GUI 编程 或 Spring 等框架的事件机制 中。下面我分 GUI 事件(最常见) 和 Spring 事件 两种情况讲,并给出示例。
JButtonActionEventActionListenerimport javax.swing.*;
import java.awt.event.*;
public class EventDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Event Demo");
JButton button = new JButton("点我");
// 注册事件监听器
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("按钮被点击了!");
}
});
frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
✅ 点击按钮 → 触发 ActionEvent → 调用 actionPerformed
| 事件 | 监听器 |
|---|---|
| 点击按钮 | ActionListener |
| 鼠标操作 | MouseListener |
| 键盘输入 | KeyListener |
| 窗口关闭 | WindowListener |
Spring 使用 事件发布-订阅机制。
public class UserRegisteredEvent extends ApplicationEvent {
public UserRegisteredEvent(Object source) {
super(source);
}
}
@Autowired
private ApplicationEventPublisher publisher;
public void registerUser() {
publisher.publishEvent(new UserRegisteredEvent(this));
}
@Component
public class UserEventListener {
@EventListener
public void onUserRegistered(UserRegisteredEvent event) {
System.out.println("用户注册成功,发送邮件");
}
}
✅ 解耦、异步友好
如果你能告诉我:
我可以给你更贴合的示例代码。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。