4. Constrained属性
一个JavaBeans的constrained属性,是指当这个属性的值要发生变化时,与这个属性已建立了某种连接的其它Java对象可否决属性值的改变。constrained属性的监听者通过抛出PropertyVetoException来阻止该属性值的改变。例:下面程序中的constrained属性是PriceInCents。
public class JellyBeans extends Canvas{
private PropertyChangeSupport changes=new PropertyChangeSupport(this);
private VetoableChangeSupport Vetos=new VetoableChangeSupport(this);
/*与前述changes相同,
可使用VetoableChangeSupport对象的实例Vetos中的方法,
在特定条件下来阻止PriceInCents值的改变。*/
......
public void setPriceInCents(int newPriceInCents) throws PropertyVetoException {
/*方法名中throws PropertyVetoException的作用是当有
其它Java对象否决PriceInCents的改变时,
要抛出例外。*/
/* 先保存原来的属性值*/
int oldPriceInCents=ourPriceInCents;
/**点火属性改变否决事件*/
vetos.fireVetoableChange("priceInCents",new Integer(OldPriceInCents),
new Integer(newPriceInCents));
/**若有其它对象否决priceInCents的改变,
则程序抛出例外,不再继续执行下面的两条语句,
方法结束。若无其它对象否决priceInCents的改变,
则在下面的代码中把ourPriceIncents赋予新值,
并点火属性改变事件*/
ourPriceInCents=newPriceInCents;
changes.firePropertyChange("priceInCents",
new Integer(oldPriceInCents),
new Integer(newPriceInCents));
}
/**与前述changes相同,
也要为PriceInCents属性预留接口,
使其它对象可注册入PriceInCents否决改变监听者队列中,
或把该对象从中注销
public void addVetoableChangeListener(VetoableChangeListener l)
{ vetos.addVetoableChangeListener(l);
}
public void removeVetoableChangeListener(VetoableChangeListener l){
vetos.removeVetoableChangeListener(l);
}
......
}
从上面的例子中可看到,一个constrained属性有两种监听者:属性变化监听者和否决属性改变的监听者。否决属性改变的监听者在自己的对象代码中有相应的控制语句,在监听到有constrained属性要发生变化时,在控制语句中判断是否应否决这个属性值的改变。
总之,某个Beans的constrained属性值可否改变取决于其它的Beans或者是Java对象是否允许这种改变。允许与否的条件由其它的Beans或Java对象在自己的类中进行定义。