一.事件机制基本概念
java中的事件机制的参与者有3种角色:
1.event object:事件状态对象,用于listener的相应的方法之中,作为参数,一般存在与listerner的方法之中
2.event listener:对每个明确的事件的发生,都相应地定义一个明确的Java方法。这些方法都集中定义在事件监听者(EventListener)接口中,
这个接口要继承 java.util.EventListener。 实现了事件监听者接口中一些或全部方法的类就是事件监听者。
3.event source:具体的事件源,比如说,你点击一个button,那么button就是event source,要想使button对某些事件进行响应,你就需要注册特定的listener。
二.举例 Door1
属性 name 和status 改变,被监管
1.Door1
public class Door1 { private String state = ""; private String name = ""; private DoorStateListener stateListener; private DoorNameListener nameListener; public void setState(String newValue) { if (state != newValue) { state = newValue; if (stateListener != null){
//注意参数传递 Door1Event event = new Door1Event(this, "state",newValue); stateListener.doorEvent(event); } } } public void setName(String newValue) { if (name != newValue) { name = newValue; if (nameListener != null){ Door1Event event = new Door1Event(this,"name", newValue); nameListener.doorEvent(event); } } } public void setStateListener(DoorStateListener stateListener) { this.stateListener = stateListener; } public void setNameListener(DoorNameListener nameListener) { this.nameListener = nameListener; } public String getState() { return state; } public String getName() { return name; } }
2.数据传递对象 Door1Event
import java.util.EventObject; public class Door1Event extends EventObject { private static final long serialVersionUID = 6496098798146410884L; private final String key ; private final String value ; public Door1Event(Object source,String key , String value) { super(source); this.key = key; this.value = value; } public String getValue() { return value; }
public String getKey() { return key; } }
3.被监管对象
Door1StateObserver
class DoorStateListener implements EventListener { public void doorEvent(Door1Event event) { if (event.getValue() != null && event.getValue().equals("open")) { System.out.println("门1打开"); } else { System.out.println("门1关闭"); } } }
Door1NameObserver
class DoorNameListener implements EventListener { public void doorEvent(Door1Event event) { Door1 door = (Door1) event.getSource(); System.out.println("I got a new name,named \"" + door.getName() + "\""); } }
4 .Door1Test
public class Door1Test { public static void main(String[] args) { Door1 door = new Door1(); door.setStateListener(new DoorStateListener()); door.setNameListener (new DoorNameListener()); // 开门 door.setState("open"); System.out.println("我已经进来了"); // 关门 door.setState("close");
// 改名
door.setName("dengzy"); } }