Property change events occur when ever there is change in the property values. We assume that the component conforms with the Java Bean specification. JavaBean s property is accessed using the set or get methods. These methods are invoked by the application for setting or getting the values from the bean. This doesn’t have any logic for the application.
Java provides PropertyChangeListener for binding the bean’s properties to the event listener. When ever a property is updated, the event will be fired and listener method executed. This example demonstrates how to write a PropertyChangeListener and attach the listener to a bean. When ever property value is changed, the method will be invoked. Lets look at the example.
- PropertyChangeListener interface extends the EventListener
- This interface has only one method propertyChange(PropertyChangeEvent evt)
BeanPropertyChangeListener.java
package javabeat.net.core; /** * Bean property change listener example * */ public class BeanPropertyChangeListener { public static void main(String[] args) { Bean bean = new Bean("Default Name","Default City"); bean.addPropertyChangeListener(new PropertyChangeListenerExample()); bean.setName("Name 1"); bean.setCity("City 1"); bean.setName("Name 2"); bean.setCity("City 2"); } }
Bean.java
package javabeat.net.core; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; public class Bean { public Bean(String name, String city) { this.name = name; this.city = city; } PropertyChangeSupport changeSupport = new PropertyChangeSupport(this); private String name; private String city; public String getName() { return name; } public void setName(String name) { changeSupport.firePropertyChange("name", this.name, name); this.name = name; } public String getCity() { return city; } public void setCity(String city) { changeSupport.firePropertyChange("city", this.city, city); this.city = city; } public void addPropertyChangeListener(PropertyChangeListener listener) { changeSupport.addPropertyChangeListener(listener); } }
PropertyChangeListenerExample.java
package javabeat.net.core; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; public class PropertyChangeListenerExample implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent evt) { System.out.println("Property Name : " + evt.getPropertyName()); System.out.println("Old Value : " + evt.getOldValue()); System.out.println("New Value : " + evt.getNewValue()); } }
Output…
Property Name : name Old Value : Default Name New Value : Name 1 Property Name : city Old Value : Default City New Value : City 1 Property Name : name Old Value : Name 1 New Value : Name 2 Property Name : city Old Value : City 1 New Value : City 2