在一个bean中设置关联属性的基本步骤如下:
调入java.beans 包,以便访问该包中所定义的一些方便类。mybutton中的import语句的使用方法如下:
import java.beans.*;
实例化java.beans.propertychangesupport类。
private propertychangesupport changes = new
propertychangesupport(this);
mybutton创建了一个名为changes的新对象,它是propertychangesupport类的实例,变量changes保存的是监听对象的集合,一旦关联属性发生变化,就会通知到这些对象。该变量定义了两个支持的方法: addpropertychangelistener和 removepropertychangelistener,这两个方法提供了公共的接口,可以让感兴趣的监听者对mybutton进行注册。
实现由propertychangesupport 类定义的方法。
propertychangesupport类包含了添加和移去监听对象的方法,尤其是propertychangelistener对象。addpropertychangelistener方法添加一个新的监听对象到表中,而removepropertychangelistener方法则从表中移去一个监听对象。propertychangesupport 类也包含第三个方法:firepropertychange,该方法把propertychangeevent对象发送给感兴趣的监听者。mybutton包含的实现添加和移去监听者方法的代码如下:
注意:参数l 表示property change listener bean,该bean可以作为注册或者移去其兴趣。
public void addpropertychangelistener(
propertychangelistener l) {
changes.addpropertychangelistener(l);
}public void removepropertychangelistener(
propertychangelistener l) {
changes.removepropertychangelistener(l);
}
修改bean的关联属性的setter方法。
对于那些打算成为关联属性的属性,可以修改bean的setter方法,以便包含当属性值变化时就发送事件的代码。mybutton在每一个设置新属性值的方法内调用firepropertychange方法。例如,当一个应用程序或者用户改变了按钮的字体时,这个动作就执行了mybutton.setfont方法。因为firepropertychange方法对于变化了的属性的新值和旧值都需要, setfont方法首先通过调用getfont方法获得旧值,之后设置新值,改变了原先的值之后,再调用changes.firepropertychange方法通知感兴趣的监听者。changes.firepropertychange方法传递了三个参数:发生变化的属性名,属性的旧值,该属性的新值。
public void setfont(font f) {
font old = getfont();
super.setfont(f);
sizetofit();
changes.firepropertychange(
"font", old, f);
}
对于firepropertychange方法来说,它完成了哪些事情?该方法把它的三个参数绑定到一个propertychangeevent对象中。之后把propertychangeevent对象作为参数,调用propertychange方法。把propertychangeevent对象传递给每个注册过的监听者。记住:propertychange把属性的旧值和新值作为对象值对待。这一点很重要,如果你的属性值是个简单类型,你就必须对该类型重新定义为对象,例如,一个简单的整数类型,在调用firepropertychange之前,就要转化为java.lang.integer。
记住:对于关联属性来说,首先是属性值发生变化,之后才发送属性变化事件。
