4. Constrained properties
A JavaBeans constrained property, which means that when the value of this property is to change, other Java objects that have established a connection with this property can veto the change in the value of the property. The listener for the constrained property prevents the property value from being changed by throwing a propertyvetoexception. Example: the constrained property in the following program is priceincents.
public class Jellybeans extends canvas{
Private Propertychangesupport changes=new Propertychangesupport (this);
Private Vetoablechangesupport vetos=new Vetoablechangesupport (this);
/* is the same as the aforementioned changes,
You can use the method in the instance Vetos of the Vetoablechangesupport object,
To prevent the change of priceincents values in certain conditions. */
......
public void setpriceincents (int newpriceincents) throws Propertyvetoexception {
/* The function of throws Propertyvetoexception in the method name is when there is
When other Java objects veto priceincents changes,
to throw an exception. */
/* First save the original attribute value * *
int oldpriceincents=ourpriceincents;
/** Ignition Attribute Change Veto event * *
Vetos.firevetoablechange ("Priceincents", New Integer (oldpriceincents),
New Integer (newpriceincents));
/** if any other object rejects the priceincents change,
The program throws an exception and does not continue with the following two statements.
Method ends. If no other object rejects the priceincents change,
The ourpriceincents is given a new value in the following code.
and Ignition Properties Change Event * *
ourPriceInCents=newPriceInCents;
changes.firePropertyChange("priceInCents",
new Integer(oldPriceInCents),
new Integer(newPriceInCents));
}
/** is the same as the aforementioned changes,
You also want to reserve an interface for the Priceincents property,
Enables other objects to be registered in the priceincents veto change listener queue,
Or unregister the object from the
public void addVetoableChangeListener(VetoableChangeListener l)
{ vetos.addVetoableChangeListener(l);
}
public void removeVetoableChangeListener(VetoableChangeListener l){
vetos.removeVetoableChangeListener(l);
}
......
}
As you can see from the example above, there are two types of listeners for a constrained attribute: The property change listener and the listener who rejects the attribute change. The listener who rejects the attribute change has a corresponding control statement in its object code, and in the control statement it is judged whether the change in the attribute value should be rejected when the constrained attribute is heard to change.
In summary, whether a beans's constrained attribute value can be changed depends on the other beans or if the Java object allows the change. The conditions allowed are defined by other beans or Java objects in their own classes.