Creating a Custom Event - Java Swing

Java examples for Swing:Introduction

Description

Creating a Custom Event

Demo Code


import java.util.EventListener;
import java.util.EventObject;

public class Main {
  public static void main(String[] args) throws Exception {
    MyClass c = new MyClass();
    // Register for MyEvents from c
    c.addMyEventListener(new MyEventListener() {
      public void myEventOccurred(MyEvent evt) {
        // MyEvent was fired
      }/* w w w  . j av a2  s . com*/
    });
  }
}

class MyEvent extends EventObject {
  public MyEvent(Object source) {
    super(source);
  }
}

interface MyEventListener extends EventListener {
  public void myEventOccurred(MyEvent evt);
}

class MyClass {
  protected javax.swing.event.EventListenerList listenerList = new javax.swing.event.EventListenerList();

  public void addMyEventListener(MyEventListener listener) {
    listenerList.add(MyEventListener.class, listener);
  }

  public void removeMyEventListener(MyEventListener listener) {
    listenerList.remove(MyEventListener.class, listener);
  }

  void fireMyEvent(MyEvent evt) {
    Object[] listeners = listenerList.getListenerList();
    for (int i = 0; i < listeners.length; i += 2) {
      if (listeners[i] == MyEventListener.class) {
        ((MyEventListener) listeners[i + 1]).myEventOccurred(evt);
      }
    }
  }
}

Related Tutorials