본문 바로가기

컴퓨터/IT

java custom event listener

자바 커스텀 이벤트 리스너 구현..

import java.util.ArrayList;
import java.util.EventListener;

/**
 * @flie    CustomEvent2.java
 * @author  Ahn Sang Hoon (sunteq)
 * @since   2009. 5. 20.
 * @version 1.0
 */

public class CustomEvent2 {

 /**
  * @param args
  */
 public static void main(String[] args) {
  new CustomEvent2();
 }
 
 public String s1 = "ash";
 
 CustomEvent2(){
  System.out.println("Hello world");
 
  MyClass c = new MyClass();
     c.addMyEventListener(new MyEventHandler());    
     c.fireMyEvent(new MyEvent("hello"));
    
 }
}


class MyEventHandler implements MyEventListener {
 public void myEventOccurred(MyEvent  evt) {
     System.out.println("MyEvent was fired1:"+evt.toString());
     System.out.println("MyEvent was fired2:"+(String)evt.getSource());
    }
}



class MyEvent {
 Object o = null;
    public MyEvent(Object source) {
        o = source;
    }
    public String getSource(){
     return o.toString();
    }
}

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

class MyClass {
   
    ArrayList<MyEventListener> listenerList = new ArrayList<MyEventListener>();

   
    public synchronized void addMyEventListener(MyEventListener l)
    {
        if(!listenerList.contains(l))
         listenerList.add(l);
    }
   
    public synchronized void removeMyEventListener(MyEventListener listener) {
        listenerList.remove(listener);
    }
   
    public int getListenerCount()
    {
        return listenerList.size();
    }

    public void fireMyEvent(MyEvent evt)
    {
        for(int i = listenerList.size() - 1; i >= 0; i--)
            ((MyEventListener )listenerList.get(i)).myEventOccurred(evt);
    }
}


참고 : http://www.exampledepot.com/egs/java.util/CustEvent.html