#navi(contents-page-name): No such page: ST
FrontPage

2022-07-31 (日) 21:36:32
  • category: swing folder: EventListener title: EventListenerを実装して独自イベント作成 tags: [EventListener, EventListenerList] author: aterai pubdate: 2004-01-26 description: イベント(イベントオブジェクト、イベントリスナー、イベントソース)を新たに作成し、これを使用します。 image: https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTMNwgwo5I/AAAAAAAAAY0/lpZGrcgRE8g/s800/EventListener.png

概要

イベント(イベントオブジェクト、イベントリスナー、イベントソース)を新たに作成し、これを使用します。
final private Vector listenerList = new Vector();
  public void addFontChangeListener(FontChangeListener listener){
    if(!listenerList.contains(listener)) listenerList.add(listener);
  }
  public void removeFontChangeListener(FontChangeListener listener){
    listenerList.remove(listener);
  }
  public void fireFontChangeEvent(String cmd, Font font){
    Vector list = (Vector)listenerList.clone();
    Enumeration enum = list.elements();
    FontChangeEvent e = new FontChangeEvent(this, cmd, font);
    while(enum.hasMoreElements()){
      FontChangeListener listener = (FontChangeListener)enum.nextElement();
      listener.fontStateChanged(e);
    }
    revalidate();
}

サンプルコード

View in GitHub: Java, Kotlin

解説

上記のサンプルではJMenuItemに設定したイベントでコンポーネントのフォントを変更できます。ラベルとボタンをその独自イベントのリスナーとして追加しているので、fireFontChangeEvent(...)メソッド内でそれらのフォントサイズが変更可能です。 Javaのイベントモデルは、delegation event model(委譲型のイベントモデル)です。
  • - リスナーの保存にVectorではなくEventListenerListを使用する場合はEventListenerListドキュメントのサンプルが参考になります。
#spanend
#spanadd
// https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/event/EventListenerList.html
#spanend
#spanadd
EventListenerList listenerList = new EventListenerList();
#spanend
#spanadd
// FontChangeEvent fontChangeEvent = null;
#spanend
#spanadd
public void addFontChangeListener(FontChangeListener l) {
#spanend
  listenerList.add(FontChangeListener.class, l);
#spanadd
}
#spanend
#spanadd
public void removeFontChangeListener(FontChangeListener l) {
#spanend
  listenerList.remove(FontChangeListener.class, l);
#spanadd
}
#spanend
#spanadd
// Notify all listeners that have registered interest for
#spanend
#spanadd
// notification on this event type.The event instance
#spanend
#spanadd
// is lazily created using the parameters passed into
#spanend
#spanadd
// the fire method.
#spanend
#spanadd
protected void fireFontChangeEvent(String cmd, Font font) {
#spanend
  // Guaranteed to return a non-null array
  Object[] listeners = listenerList.getListenerList();
  FontChangeEvent evt = new FontChangeEvent(this, cmd, font);
  // Process the listeners last to first, notifying
  // those that are interested in this event
  for (int i = listeners.length - 2; i >= 0; i -= 2) {
    if (listeners[i] == FontChangeListener.class) {
      // Lazily create the event:
      // if (fontChangeEvent == null)
      //   fontChangeEvent = new FontChangeEvent(this);
      ((FontChangeListener) listeners[i + 1]).fontStateChanged(evt);
    }
  }
#spanadd
}
#spanend
#spanadd

参考リンク

コメント