JavaBeans 程序开发从入门到精通教程2

豆豆网   技术应用频道   2006年04月01日  【字号: 收藏本文

本文详细介绍JavaBeans 程序开发从入门到精通教程2

  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));
}

责编:豆豆技术应用

正在加载评论...