Search code examples
javaexceptionjavabeanspropertychanged

Can I throw exception with java bean


I want to notify to class1 with exception that can or cannot change a variable. I have tried to put in propertyChange to throw a exception but i can't with this method. how can I notify class1??

class1 ->

public void setProperty(int var) {
    if(var > 0){
    propertySupport.firePropertyChange("var", this.var,var);
    this.var = var;
    }else{
       System.out.println("bla bla"); 
    }
}

//methods
public void addPropertyChangeListener(PropertyChangeListener listener) {
    propertySupport.addPropertyChangeListener(listener);
}

public void removePropertyChangeListener(PropertyChangeListener listener) {
    propertySupport.removePropertyChangeListener(listener);
}

class2 ->

@Override
public void propertyChange(PropertyChangeEvent evt){
    if(evt.getNewValue().equals("var"))
       //TODO
    }else{
       //throw exception to not change var in class1
    }

Solution

  • You need to use VetoableChangeListener.

    See JavaDoc:

    public interface VetoableChangeListener extends EventListener

    A VetoableChange event gets fired whenever a bean changes a "constrained" property. You can register a VetoableChangeListener with a source bean so as to be notified of any constrained property updates.

    void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException

    This method gets called when a constrained property is changed.

    Parameters: evt - a PropertyChangeEvent object describing the event source and the property that has changed. Throws: PropertyVetoException - if the recipient wishes the property change to be rolled back.