一个对象如何得知另一对象处理了某个事件..
有一个JFrame类,它有一个JDialog的属性,
而JDialog里有一个JButton属性.
现在触发JButton的Click事件,JFrame 怎样才可以知道JDialog里的JButton的事件发
生了?怎样知道处理结束了?
------解决方案--------------------观察者模式的通例
import java.util.Observer;
public class Tester {
static private Watched watched;
static private Observer watcher;
public static void main(String[] args) {
watched = new Watched();
watcher = new Watcher(watched);
watched.changeData( "In C, we create bugs. ");
watched.changeData( "In Java, we inherit bugs. ");
watched.changeData( "In Java, we inherit bugs. ");
watched.changeData( "In Visual Basic, we visualize bugs. ");
}
}
import java.util.Observable;
public class Watched extends Observable {
private String data = " ";
public String retrieveData() {
return data;
}
public void changeData(String data) {
if (!this.data.equals(data)) {
this.data = data;
setChanged();
}
notifyObservers();
}
}
import java.util.Observable;
import java.util.Observer;
public class Watcher implements Observer {
public Watcher(Watched w) {
w.addObserver(this);
}
public void update(Observable ob, Object arg) {
System.out.println( "Data has been changed to: ' "
+ ((Watched) ob).retrieveData() + " ' ");
}
}
配合参阅观察者模式一起使用