本文介绍了Java属性更改侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要处理2个类之间的更改交互.

i need to handle a change-interaction between 2 classes.

public class HeadClass {

private Subclass sub;

public void refresh() {...}

}


public class Subclass{

ArrayList store;

public void add(T data)
store.add(data);
firePropertyChange(...);
}

每当在子类中调用方法"add"时,应在HeadClass中调用方法"refresh"!但是我应该在哪个类中实现这一行:

Whenever the method "add" in the subclass is called the method "refresh" in HeadClass should be called!But in which class i should implement this line:

private PropertyChangeSupport changes = new PropertyChangeSupport(/*WHAT SHOULD BE HERE?*/);

如果我在HeadClass中实现它,我可以这样反应:

If i implement it in the HeadClass i can react like this:

changes.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent event) {
                refresh();
            }
        });

但是如果我无法访问propertyChangeSupport"changes",该如何从子类中触发propertyChangeEvents?

But how should i fire propertyChangeEvents from the Subclass if i cant access the propertyChangeSupport "changes"??

推荐答案

SubClass获得PropertyChangeSupport,以及添加和删除PropertyChangeListener的方法.您可以将 this 传递到子类的PropertyChangeSupport构造函数中.

SubClass gets PropertyChangeSupport, and methods to add and remove the PropertyChangeListener's. You would pass this into SubClass's PropertyChangeSupport constructor.

public class Subclass{
  private PropertyChangeSupport propChangeSupport =
       new PropertyChangeSupport(this);
  private ArrayList store;

  public void addPropertyChangeListener(PropertyChangeListener listener) {
    propChangeSupport.addPropertyChangeListener(listener);
  }

  public void removePropertyChangeListener(PropertyChangeListener listener) {
    propChangeSupport.removePropertyChangeListener(listener);
  }


  public void add(T data)
    store.add(data);
    propChangeSupport.firePropertyChange(...);
  }


}

关键始终是哪个类需要监听其状态?由于这是SubClass,因此它需要持有属性更改支持.进行侦听的类是将侦听器添加到支持的类.

The key is always what class needs to have its state listened to? Since that is the SubClass, then it needs to hold the property change support. The class that does the listening is the one that adds the listener to the support.

这篇关于Java属性更改侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 10:40