Reputation: 69
import java.beans.PropertyVetoException;
public class Main {
public static void main(String[] args) {
Purchase purch = new Purchase("Computer");
PurchaseView pView = new PurchaseView();
purch.addPropertyChangeListener(pView);
try {
purch.setData("Notebook");
System.out.println(purch);
} catch (PropertyVetoException exc) {
System.out.println(exc.getMessage());
}
}
}
There you have Purchase and PurchaseView classes:
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyVetoException;
public class Purchase {
private String data;
private PropertyChangeSupport propertyChange = new PropertyChangeSupport(this);
public Purchase(String data) {
this.data = data;
}
public synchronized void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChange.addPropertyChangeListener(listener);
}
public synchronized void removePropertyChangeListener(PropertyChangeListener l) {
propertyChange.removePropertyChangeListener(l);
}
public String getData() {
return data;
}
public void setData(String data) {
String oldValue = data;
this.data = data;
propertyChange.firePropertyChange("data", oldValue, data);
}
}
}
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public class PurchaseView implements PropertyChangeListener{
public PurchaseView() {}
@Override
public void propertyChange(PropertyChangeEvent evt) {
String propName = evt.getPropertyName();
if(propName.equals("data")) {
String oldValue = (String) evt.getOldValue();
String newValue = (String) evt.getNewValue();
System.out.println("Change value of: " + evt.getPropertyName() + " from: " + oldValue + " to: " + newValue);
}
}
}
I want the program to produce output as it is shown in PurchaseView class when the data attribute is changed. It seems to be well implemented to me, but it doesn't work.
Any ideas?
Upvotes: 1
Views: 71
Reputation: 26
what is your output?
I think u just made a mistake taking the oldValue in your setData method. Should be something like this:
public void setData(String data) {
String oldValue = this.data;
this.data = data;
propertyChange.firePropertyChange("data", oldValue, data);
}
Note you forget the this
reserved word at the first line of setData method, wich means that u take the method variable instead the class variable.
Upvotes: 1