java怎样监听一个值是否发生了变化,具体代码

如题所述

第1个回答  2017-07-03
java 自定义监听器监听属性变化
import java.util.EventObject;

public class MyEvent extends EventObject
{
private Object obj;
private String sName;

public MyEvent(Object source,String sName)
{
super(source);
this.obj=source;
this.sName=sName;
}

public Object getObj()
{
return obj;
}

public String getsName()
{
return sName;
}
}

import java.util.EventListener;

public interface MyEventListener extends EventListener
{

public void handleEvent (MyEvent me);

}

import java.util.Iterator;
import java.util.Vector;

import demo.DemoEvent;

public class MyEventSource
{
private Vector list=new Vector();
private String sName = "";

public MyEventSource()
{
super();
}
public void addMyEventListener(MyEventListener me)
{
list.add(me);
}
public void deleteMyEventListener(MyEventListener me)
{
list.remove(me);
}
public void notifyMyEvent(MyEvent me)
{
Iterator it=list.iterator();
while(it.hasNext())
{
((MyEventListener) it.next()).handleEvent(me);
}
}
public void setName(String str)
{
boolean bool = false;
if (str == null && sName != null)
bool = true;
else if (str != null && sName == null)
bool = true;
else if (!sName.equals(str))
bool = true;
this.sName = str;
// 如果改变则执行事件
if (bool)
notifyMyEvent(new MyEvent(this, sName));
}
public String getsName()
{
return sName;
}

}

public class Test implements MyEventListener
{
public Test()
{
MyEventSource mes = new MyEventSource();
mes.addMyEventListener(this);
mes.setName("niu");
}

public static void main(String args[])
{
new Test();
}

public void handleEvent(MyEvent me)
{
System.out.println(me.getSource());
System.out.println(me.getsName());
}
}
相似回答