JavaBean PropertyChangeEvent 事件使用

In this example we'll listen to bean's property change event. We create a small bean named MyBean, adds attributes and getter/setter. We want to know or to get notified when the bean property name is changed.

First we need the add a PropertyChangeSupport field to the bean, with this object we will fire the property change event. When we need to listen for the change we have to create an implementation of aPropertyChangeListener. In this example we'll just use the MyBean class as the listener.

The PropertyChangeListener has a method called propertyChange and inside this method we'll implementing the code to get the event fired by the PropertyChangeSupport.

package org.kodejava.example.bean;

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

public class MyBean implements PropertyChangeListener, Serializable {
    private Long id;
    private String name;

    private PropertyChangeSupport pcs = new PropertyChangeSupport(this);

    public MyBean() {
        pcs.addPropertyChangeListener(this);
    }

    /**
     * This method gets called when a bound property is changed.
     *
     * @param evt A PropertyChangeEvent object describing the event source
     *            and the property that has changed.
     */
    public void propertyChange(PropertyChangeEvent evt) {
        System.out.println("Name      = " + evt.getPropertyName());
        System.out.println("Old Value = " + evt.getOldValue());
        System.out.println("New Value = " + evt.getNewValue());
    }

    public static void main(String[] args) {
        MyBean bean = new MyBean();
        bean.setName("My Initial Value");
        bean.setName("My New Value");
        bean.setName("My Yet Another Value");
    }


    //~ --------------------------------------------- Bean's Getters and Setters

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        String oldValue = this.name;
        this.name = name;

        //
        // Fires a property change event
        //
        pcs.firePropertyChange("name", oldValue, name);
    }
}


转载于:https://my.oschina.net/jsan/blog/57634

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值