Creating a Custom Event

|

-----------------------------------------------------------

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

import javax.swing.event.EventListenerList;

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

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

class MyClass {
  protected EventListenerList listenerList = new 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 = i+2) {
      if (listeners[i== MyEventListener.class) {
        ((MyEventListenerlisteners[i+1]).myEventOccurred(evt);
      }
    }
  }
}

public class Main {
  public static void main(String[] argvthrows Exception {
    MyClass c = new MyClass();
    c.addMyEventListener(new MyEventListener() {
      public void myEventOccurred(MyEvent evt) {
        System.out.println("fired");
      }
    });

  }
}

 

--------------------------------------------

 

This is an example of custom event classes made to monitor the folder for changes ie. when some change is made in the folder, the event is fired. 
This connects this topic to the topic regarding folder listener from the archive : 
http://forums.sun.com/thread.jspa?threadID=482409&start=0&tstart=0

So, in order to make an custom event first you have to define your event in a class that will extends EventObject class from java.util package.

// class that defines the custom event
import java.util.EventObject;
public class FolderEvent extends EventObject {
       public FolderEvent(Object source){
       super(source);
       }
}



Secondly, you have to define an interface which will represent the contract for making the listener

public interface FolderListenerInterface {
     //you need to override this method to add some functionality as a response to the event 
     public void handleFolderEvent(FolderEvent e);
}





Then, you have to make an class that will fire your event when some specific event occurs. 
Monitor.java starts a low priority thread in which it periodically ( in 1sec interval )checks the folder for some changes and if any it fires an FolderEvent.


import java.io.File;
import java.util.ArrayList;
import java.util.Date;
 
public class Monitor extends Thread{
 
//a list of listeners  -  contains a references to all classes that are interested in listening to FolderEvent
private ArrayList listeners = new ArrayList();
 
//dir - monitored directory
private File dir;
 
//constructor - starts a low priority thread
public Monitor(){
    this.start();
    this.setPriority(Thread.MIN_PRIORITY);	
}
 
//register new listener
public void addFolderListener(FolderListenerInterface folderListener){
     listeners.add(folderListener);
}
 
//removes the listener
public void removeFolderLIstener(FolderListenerInterface folderListener){
     listeners.remove(folderListener);
}
 
void dispatchEvent(){
     for(int i=0;i<listeners.size();i++){
          FolderListenerInterface folderListener = (FolderListenerInterface)listeners.get(i);
          if (folderListener != null){
               FolderEvent folderEvent = new FolderEvent(this);
               folderListener.handleFolderEvent(folderEvent);
          }	
     }
}
 
public void run(){
      dir = new File("C:\\FolderToBeMonitored");
      Date lastChange = new Date(dir.lastModified());
 
      while(true){
                Date change = new Date(dir.lastModified());
 
                if(change.after(lastChange)){       //event occurred
                dispatchEvent();                //dispatching event to all listeners
                lastChange = change;
           }
 
           try{
                Thread.sleep(1000);          
           }catch(InterruptedException e){}	
     }	
}	
}





And as the last thing to write, here is an simple app that uses the classes above

public class FolderListenerApp {
 
     public static void main(String[] args) {
     Monitor m = new Monitor();
 
     m.addFolderListener(new FolderListenerInterface(){
          public void handleFolderEvent(FolderEvent fe){
          System.out.println("EVENT  OCCURRED");		
          }
     });
		
     }
}

'개발/활용정보 > Java' 카테고리의 다른 글

ant 사용법  (0) 2011.04.19
Ant 태스크  (0) 2011.04.19
eclipse 단축키  (0) 2011.04.13
자바가 사용하는 메모리의 종류와 특징  (0) 2011.04.13
Java 메모리 설정 MaxPermSize  (0) 2011.04.13
And