rcp 监听属性改变

0down vote

I'm sure there are many ways of doing this, but I've used the JFace IPropertyChangeListener interface in the past for simple event propagation.

Make your view implement IPropertyChangeListener. Create a Singleton class that you can register your IPropertyChangeListener with, and send a PropertyChangeEvent to. Then in the constructor of your view, register it with your Singleton.

Now you can get hold of your Singleton in your editor and fire off an event that will get picked up in your view.

Example code for the Singleton:

public class PropertyChangeEventBus {

    private static PropertyChangeEventBus s_instance = new PropertyChangeEventBus();

    public static PropertyChangeEventBus instance()
    {
        return s_instance;
    }

    private Set<IPropertyChangeListener> m_listeners;

    private PropertyChangeEventBus()
    {
        // use CopyOnWriteArraySet to prevent ConcurrentModificationExceptions
        m_listeners = new CopyOnWriteArraySet<IPropertyChangeListener>();
    }

    public void addListener(IPropertyChangeListener listener)
    {   
        m_listeners.add(listener);       
    }

    public void removeListener(IPropertyChangeListener listener)
    {
        m_listeners.remove(listener);
    }

    public void fire(final PropertyChangeEvent event)
    {   
        // run property change events in UI thread to prevent having to have lots of syncExecs in the listener methods
        ViewUtils.syncExec(new Runnable()
        {           
            @Override
            public void run()
            {
                for (IPropertyChangeListener listener : m_listeners) 
                {
                    try
                    {
                        listener.propertyChange(event);
                    }
                    catch(Exception e)
                    {                       
                        //log it, present error message
                    }
                }
            }
        });     
    }
}

Example Code for the View:

//The constructor
public MyView() 
{
    PropertyChangeEventBus.instance().addListener(this);
}

@Override
public void propertyChange(PropertyChangeEvent event)
{
    if(event.getProperty().equals(SOME_CONSTANT))
    {           
        // Refresh View         
    }
}

转载于:https://my.oschina.net/zhenghuazhi/blog/834454

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值