在 Java 中,“Event 事件怎样触发”通常取决于你使用的是哪种事件机制。下面我按常见场景给你说明,并给出示例。
Java GUI 使用 事件委托模型:
ActionEventimport javax.swing.*;
import java.awt.event.*;
public class Demo {
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(200, 100);
frame.setVisible(true);
}
}
✅ 触发方式:用户点击按钮(JVM 内部自动触发)
import java.util.EventObject;
public class MyEvent extends EventObject {
public MyEvent(Object source) {
super(source);
}
}
import java.util.EventListener;
public interface MyEventListener extends EventListener {
void onEvent(MyEvent event);
}
import java.util.*;
public class EventSource {
private List<MyEventListener> listeners = new ArrayList<>();
public void addListener(MyEventListener l) {
listeners.add(l);
}
// 手动触发事件
public void fireEvent() {
MyEvent event = new MyEvent(this);
for (MyEventListener l : listeners) {
l.onEvent(event);
}
}
}
public class Test {
public static void main(String[] args) {
EventSource source = new EventSource();
source.addListener(e -> System.out.println("事件被触发"));
source.fireEvent(); // 手动触发
}
}
✅ 触发方式:调用 fireEvent() 方法
import org.springframework.context.ApplicationEvent;
public class UserEvent extends ApplicationEvent {
public UserEvent(Object source) {
super(source);
}
}
@Autowired
private ApplicationEventPublisher publisher;
publisher.publishEvent(new UserEvent(this));
@Component
public class UserEventListener {
@EventListener
public void handle(UserEvent event) {
System.out.println("收到用户事件");
}
}
✅ 触发方式:publishEvent()
| 场景 | 触发方式 |
|---|---|
| Swing / AWT | 用户操作自动触发 |
| 自定义事件 | 手动调用触发方法 |
| Spring Event | publishEvent() |
如果你能告诉我你指的是 Swing / Spring / 自定义事件 / 多线程,我可以给你更精确的示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。