JavaBeans的PropertyChangeListener系列类用法

类图如下:

JavaBeans的PropertyChangeListener系列类用法_第1张图片


顺序图如下:



示例代码如下:

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


public final class PropertyChanger
{
   public PropertyChanger()
   {
      // TODO Auto-generated constructor stub
      pcs = new PropertyChangeSupport(this);
      pcs.addPropertyChangeListener(new UnnamedPropertyChangeListener(this));
      pcs.addPropertyChangeListener("name", new PropertyChangeListenerWithName(this));
   }

   /**
    * @param args
    */
   public static void main(String[] args)
   {
      // TODO Auto-generated method stub
      PropertyChanger pc = new PropertyChanger();
      pc.run();
   }

   public void run()
   {
      setName("virus");
      setId(1);
   }

   public String getName()
   {
      return name;
   }

   public void setName(String name)
   {
      String oldName = this.name;
      this.name = name;
      pcs.firePropertyChange("name", oldName, name);
   }

   public int getId()
   {
      return id;
   }

   public void setId(int id)
   {
      int oldId = this.id;
      this.id = id;
      pcs.firePropertyChange("id", oldId, id);
   }

   private PropertyChangeSupport pcs;

   private String name = "world";
   private int id = 0;

}

class UnnamedPropertyChangeListener implements PropertyChangeListener
{
   /**
    * @param changer
    */
   public UnnamedPropertyChangeListener(PropertyChanger changer)
   {
      super();
      this.changer = changer;
   }

   @Override
   public void propertyChange(PropertyChangeEvent evt)
   {
      // TODO Auto-generated method stub
      if (evt.getSource() == changer)
      {
         if (evt.getPropertyName().equals("name") || evt.getPropertyName().equals("id"))
         {
            System.out.println("My new " + evt.getPropertyName() + " is: " + evt.getNewValue() + ".");
         }
         else
         {
            System.out.println("Unlnown property.");
         }
      }
   }

   private PropertyChanger changer;

}

class PropertyChangeListenerWithName implements PropertyChangeListener
{

   /**
    * @param changer
    */
   public PropertyChangeListenerWithName(PropertyChanger changer)
   {
      super();
      this.changer = changer;
   }

   @Override
   public void propertyChange(PropertyChangeEvent evt)
   {
      // TODO Auto-generated method stub
      if (evt.getSource() == changer)
      {
         if (evt.getPropertyName().equals(propName))
         {
            System.out.println("Hello, " + evt.getNewValue() + " !");
         }
         else
         {
            System.out.println("Unlnown property.");
         }
      }
   }

   private PropertyChanger changer;

   private final String propName = "name";

}


你可能感兴趣的:(String,Class,import,Constructor,javabeans)