Specifying Dynamic Default Values and Property Persistence

To set a default value for a property, you can specify a DefaultValueAttribute attribute when creating a new PropertyInfo object, as described in Specifying Custom Property Attributes. In some cases, you might want to specify a default value dynamically — that is, a value calculated at run time. Similarly, you might want to specify that a property value is persisted (saved between design-time sessions) based on run time conditions.

In this topic you can find information about:

Setting Persistence for Property Values

By default, when a control property value is changed from the default at design time (as in the Properties window), it is saved whenever the host control is saved. For example, if your control is instantiated in a Visual J++ form, and if you change the value of a property in the Properties window, the property's value is saved when you save the form. For efficiency, if the property value matches its default value, the value is not persisted.

In rare instances you want to specify that a value is persisted based on a run time condition. To control persistence, override the Control class' shouldPersist<property> method. After testing for the condition, the method should return a Boolean value indicating whether the custom value should be saved. To prevent the value from being saved, return false from this method. You can also override the shouldPersist<property> for properties inherited from the superclass, as in this example, which sets persistence of the font property depending on whether the font has changed:

public boolean shouldPersistFont() {
   return font != null;
}

Note   Ambient properties (whose value is inherited from the parent) such as font and backColor return null when compared as illustrated above to represent that they are set to the default values. However, explicitly getting the value of such properties — for example, calling the getFont method — returns the actual font information.

Calculating Dynamic Default Values

To create a default value for a property at run time, create a reset<property> method for that property. The following example shows how you can implement a default value based on today's date for a property called lastUpdate:

private Date dtLastUpdate;
public void setLastUpdate( Date d ){
   dtLastUpdate = d ;
   invalidate();   // Repaint control when property changes
}

public void resetLastUpdate(){
   return new Date();
}

You can also override the reset<property> methods inherited from the Control class. The following example shows how you can override the resetFont method for your control:

public void resetFont() {
   Font f = new Font("Arial", 8.0f, FontSize.POINTS, FontWeight.BOLD,
       false, false, false);
   setFont(f);
}