How to Write Bean PropertyChangeListener in Java

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)

 * 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");


import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

public class Bean {
 public Bean(String name, String city) { = name; = 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",, name); = name;

 public String getCity() {
 return city;

 public void setCity(String city) {
 changeSupport.firePropertyChange("city",, city); = city;

 public void addPropertyChangeListener(PropertyChangeListener listener) {


import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

public class PropertyChangeListenerExample implements PropertyChangeListener {
 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());


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

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!