How do I create a constrained property?

John Zukowski

Constrained properties have the following pattern:

public TYPE getXXX()
public void setXXX(TYPE value) 
       throws PropertyVetoException

where PropertyVetoException is thrown if the validation fails.

You need to implement a pair of methods to maintain list of vetoable change listeners:

public void addVetoableChangeListener(VetoableChangeListener x)
public void removeVetoableChangeListener(VetoableChangeListener x)

The utility class VetoableChangeSupport is available to do most of the work for you, managing the list and providing notification support.

The registration support would look like:

private VetoableChangeSupport vetoes = 
  new VetoableChangeSupport(this);

public void addVetoableChangeListener(
              VetoableChangeListener v) {
  vetoes.addVetoableChangeListener(v);
}

public void removeVetoableChangeListener(
              VetoableChangeListener v) {
  vetoes.removeVetoableChangeListener(v);
}

The constrained property would then look something like the following:

public void setMood(int mood)
       throws PropertyVetoException {
  vetoes.fireVetoableChange("mood",
      new Integer(this.mood), new Integer(mood));
  int old = this.mood;
  this.mood = mood;
  repaint();
}

And the object interested in validating the change would need:

public void vetoableChange(
                 PropertyChangeEvent e)
    throws PropertyVetoException { 
  ...
}

Frequently, a constrained property is also bound. This would result in the following property setter method:

public void setMood(int mood)
       throws PropertyVetoException {
  vetoes.fireVetoableChange("mood",
      new Integer(this.mood), new Integer(mood));
  int old = this.mood;
  this.mood = mood;
  repaint();
  changes.firePropertyChange("mood",
            new Integer(old), new Integer(mood));
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact