在Java中,事件監聽器(EventListener)是用于處理特定類型事件的接口。要處理事件,你需要遵循以下步驟:
MyListener
的接口:public interface MyListener {
void onEventOccurred(String message);
}
EventPublisher
的類:import java.util.ArrayList;
import java.util.List;
public class EventPublisher {
private List<MyListener> listeners = new ArrayList<>();
public void addListener(MyListener listener) {
listeners.add(listener);
}
public void removeListener(MyListener listener) {
listeners.remove(listener);
}
public void triggerEvent(String message) {
for (MyListener listener : listeners) {
listener.onEventOccurred(message);
}
}
}
MyListenerImpl
的類:public class MyListenerImpl implements MyListener {
private String name;
public MyListenerImpl(String name) {
this.name = name;
}
@Override
public void onEventOccurred(String message) {
System.out.println(name + " received event: " + message);
}
}
EventPublisher
對象,然后創建一個或多個MyListener
實現類的實例。將監聽器添加到發布者中,并觸發事件。public class Main {
public static void main(String[] args) {
EventPublisher publisher = new EventPublisher();
MyListener listener1 = new MyListenerImpl("Listener 1");
MyListener listener2 = new MyListenerImpl("Listener 2");
publisher.addListener(listener1);
publisher.addListener(listener2);
publisher.triggerEvent("Hello, World!");
}
}
運行此程序后,你將看到以下輸出:
Listener 1 received event: Hello, World!
Listener 2 received event: Hello, World!
這就是如何在Java中使用事件監聽器處理事件的基本過程。你可以根據需要擴展和修改這些示例,以適應你的具體需求。