-1

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
    }
Liru
  • 13
  • 2
  • `if(evt.getNewValue() == "var")`??? No, don't compare Strings with `==` as this compares *references*, which is not what you want to do. Use the `.equals(...)` method instead. – Hovercraft Full Of Eels Jun 07 '17 at 21:51
  • And property change should not be used to pass exceptions. It is only for notification of change in state, and nothing else. How the listening class responds to the change in state is up to it. – Hovercraft Full Of Eels Jun 07 '17 at 21:52
  • so, how i notify class1 not to change var? – Liru Jun 07 '17 at 21:55

2 Answers2

1

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.

tsolakp
  • 5,858
  • 1
  • 22
  • 28
0

FirePropertyChange would tell me to change a variable or attribute that I'm interested in using. You should validate whether or not to change the variable in the same "setProperty" method then to notify class 2 that that value has changed

class1

public void setProperty(int var) {

if(this.var != var && var > 0){
   propertySupport.firePropertyChange("var", this.var,var);
   this.var = var;
}else{
   System.out.println("bla bla"); 
}

}

class2

@Override
public void propertyChange(PropertyChangeEvent evt){
if(evt.getPropertyName().equals("var")){

   //I do something with this new variable
   System.out.print(evt.getNewValue());
}else{
   //throw exception to not change var in class1
}