易网时代-编程资源站
Welcome
微信登录
首页
/
操作系统
/
Linux
/
Java 自定义监听器监听属性变化
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());
}
}
版权所有©石家庄振强科技有限公司2024
冀ICP备08103738号-5
网站地图