Java/Swing JFC/EventListenerList

Материал из Java эксперт
Перейти к: навигация, поиск

Use EventListenerList to store event listener list

 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.EventListenerList;
class DualListener implements ActionListener, ChangeListener {
  public void actionPerformed(ActionEvent e) {
    System.out.println("dual: Action " + e);
  }
  public void stateChanged(ChangeEvent e) {
    System.out.println("dual: Change " + e);
  }
}
public class Main {
  public Main() {
    MyObject pair = new MyObject("This is "a"", "This is "b"");
    ActionListener al = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("al: Action " + e);
      }
    };
    DualListener dual = new DualListener();
    pair.addActionListener(al);
    pair.addChangeListener(dual);
    pair.setA("new A");
    pair.setB("new B");
    pair.addActionListener(dual);
    pair.setA("another A");
    pair.removeActionListener(dual);
    pair.setB("another B");
    pair.setA("final A");
  }
  public static void main(String arg[]) {
    new Main();
  }
}
class MyObject {
  Object a = null, b = null;
  EventListenerList events = new EventListenerList();
  ActionEvent actionEvent; 
  ChangeEvent changeEvent;  
  public MyObject(Object a1, Object b1) {
    a = a1;
    b = b1;
  }
  public void addActionListener(ActionListener listener) {
    events.add(ActionListener.class, listener);
  }
  public void removeActionListener(ActionListener listener) {
    events.remove(ActionListener.class, listener);
  }
  public void addChangeListener(ChangeListener listener) {
    events.add(ChangeListener.class, listener);
  }
  public void removeChangeListener(ChangeListener listener) {
    events.remove(ChangeListener.class, listener);
  }
  public void setA(Object newA) {
    a = newA;
    fireAChanged();
  }
  public void setB(Object newB) {
    b = newB;
    fireBChanged();
  }
  protected void fireAChanged() {
    Object[] listeners = events.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2) {
      if (listeners[i] == ActionListener.class) {
        if (actionEvent == null) {
          actionEvent = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "a");
        }
        ((ActionListener) listeners[i + 1]).actionPerformed(actionEvent);
      }
    }
  }
  protected void fireBChanged() {
    Object[] listeners = events.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2) {
      if (listeners[i] == ChangeListener.class) {
        if (changeEvent == null) {
          changeEvent = new ChangeEvent(this);
        }
        ((ChangeListener) listeners[i + 1]).stateChanged(changeEvent);
      }
    }
  }
}