Custom event in java

Java: Creating a custom event

Here’s an example of how create your own events and listen to them. It’s called the observer pattern. In this example the initiator prints «Hello» and the HelloListener responds with «Hello there!».

// An interface to be implemented by everyone // interested in "Hello" events interface HelloListener < void someoneSaidHello(); > 
// Someone who says "Hello" class Initiater < private List listeners = new ArrayList(); public void addListener(HelloListener toAdd) < listeners.add(toAdd); >public void sayHello() < System.out.println("Hello!"); // Notify everybody that may be interested. for (HelloListener hl : listeners) hl.someoneSaidHello(); > > 
// Someone interested in "Hello" events class Responder implements HelloListener < @Override public void someoneSaidHello() < System.out.println("Hello there!"); > > 

And here’s a little example runner:

class Test < public static void main(String[] args) < Initiater initiater = new Initiater(); Responder responder = new Responder(); initiater.addListener(responder); initiater.sayHello(); // "Hello!" and "Hello there!" > > 

Comments (2)

Than you for this example. It works perfectly!

Источник

Java: Custom Events Tutorial

pub-sub

As i can see inside JButton Class, it simply uses Publish-Subscribe Pattern for Implementation of Events
these patterns are defines One-to-Many Communication

An Object has a list of Subscribers, when Something happens ,the object will tell everyone on the list about the thing that happened.
Now, How the subscriber will know What things Should listen to OR How Room will tell the subscribers about supported Events.
Here is the role of Listener, the Listener is the one who know about events exposed by the Object.
So now the Subscriber will use Listener to listen to events exposed by the Object.
Listener = Interface between Object and Subscriber

Читайте также:  Css background image over image

Let’s Do it

  • a Room (The Object) which has two Events
  • a MainWindow (The Subscriber) which is interested in Room Events
  • RoomListener (The Listener) which knows about Room Events and will tell Subscriber about the events.

So, Now converting this to Java will result in:

  1. a class to represent the Room (Object)
  2. a class to represent the RoomListener (Listener)
  3. a class to represent the MainWindow (Subscriber)

The Object:

Room Class

Start by Creating a new Class called Room.java

make a place to store Persons inside it

public class Room < /* Store Persons inside Room */ ListPersonsList = new ArrayList<>(); public Room() < /* Just Empty Constructor */ >>

The List is like the Array in C++, but here you can add new element or remove an element during runtime.
So, List is an array with variable length during Runtime.

Now, we will add a two basic functions to our Room Class

/* Add New Person to PersonsList */ public void AddPerson(Person PersonInfo) < //Add Person to List PersonsList.add(PersonInfo); >/* Remove a Person from PersonsList */ public void RemovePerson(Person PersonInfo) < //Remove a Person from List PersonsList.remove(PersonInfo); >
Person Class

make a new file called Person.java and put the following code

it just a simple class to represent a person
_________________________________________________________________________

TheListener

make a new Class Called RoomListener.java

public abstract class RoomListener

Why we make it abstract class ?
Because, abstract classes can’t be instantiated, it doesn’t make sense to allow instantiation of empty class
So Something like

RoomListener Rl = new RoomListener() //is not valid

Add The Following Two Functions to RoomListener Class

public abstract void TellMeWhoComes(Person PersonInfo); public abstract void TellMeWhoLeaves(Person PersonInfo);

TellMeWhoComes(): will called by Room whenever a Person enters the room
TellMeWhoLeaves(): will called by Room whenever a Person leaves the room

Now let’s go back to Room class

Back to Object

Open Room.java and Now we will implement listeners list and when events will be fired.

1. Implementing Listeners List

add the following definition

List listeners = new ArrayList<>();

add the following function, so a subscriber can add new listener to the list

/* Add New RoomListener to the List of Listeners */ public void AddRoomListener(RoomListener pl)

2. Implementation of Event Firing
Modify Function AddPerson(), So it will look like this

/* Add new Person to PersonsList */ public void AddPerson(Person PersonInfo) < //Add Person to List PersonsList.add(PersonInfo); // Notify All Subscribers that a New Person has Entered the Room for (RoomListener p : listeners) < p.TellMeWhoComes(PersonInfo); >>

What we added here is for loop on all listeners in the list to notify them about the person entered the room.

Modify Function RemovePerson(), So it will look like this

/* Remove a Person from PersonsList */ public void RemovePerson(Person PersonInfo) < //Remove a Person From List PersonsList.remove(PersonInfo); // Notify All Subscribers that a Person has left the Room for (RoomListener p : listeners) < p.TellMeWhoLeaves(PersonInfo); >>
The Subscriber

The Subscriber is the class which will use listener to catch the events fired by Room

if you are building a GUI application then open your JFrame class and do the following:

1. Create New Instance of Room

Room EmbeddedSystemsRoom = new Room();
public MainWindow() < initComponents(); /* MainWindow (Subscriber) will Add a new Listener */ EmbeddedSystemsRoom.AddRoomListener(new RoomListener() < /* I'm interested to know who Enters the Room */ @Override public void TellMeWhoComes(Person p) < /* Do Whatever you want here */ /* in this example: it will update a label on the UI */ lbl_LastEnter.setText(p.Name); >/* I'm interested to know who Leave the Room */ @Override public void TellMeWhoLeaves(Person p) < /* Do Whatever you want here */ /* in this example: it will update a label on the UI */ lbl_LastExit.setText(p.Name); >>);

Finally: I hope this Tutorial give you a good start with Custom Events in Java

Источник

Custom Events In Java

The Delegation Event Model is used in Java to handle events. AWT and Swing API provides many event listener and adapter classes to handle various type of events on GUI components. In this blog post, I’m writing about creating and handling non-UI and custom events in Java.

Non-UI and custom events are common in applications. We usually write the event handling code for such events in methods and mock the occurrence of an event as a method call. If the event handling code varies then we employ overloading or overriding or loose-coupling by providing many class implementations for an interface. When we want even more flexibility of enabling or disabling the execution of event handler method then we often use a boolean flag within the method to decide whether the business logic in it should be executed. Writing code to enable/disable execution within method by using multiple boolean flags when you need to enable/disable multiple events on a common source can be quite complex.

It is easy to mimic event occurrence as method calls. However, when you want the flexibility of enabling or disabling the event handling then it is easier to code the event as custom event. All events in Java are subclasses of EventObject . The custom event class should also extend this class.

An example of a custom event is the request for approval when a new workflow request is created. For writing custom event handling code these classes are required – event class, event listener, event source class, class implementing event listener or adapter class.

The event class is given in Listing 1. The event listener is given in Listing 2. The event source class is given in Listing 3. The event listener implementation class is given in Listing 4. Code to fire event is given in Listing 5 and code to instantiate and assign event listener implementation class and register the event listener is given in Listing 6.

public class ApproveRequestEvent extends EventObject < public ApproveRequestEvent(WorkflowRequest request) < super(request); >>

public interface WorkflowRequestStateChangeListener

public class WorkflowRequest < private List<WorkflowRequestStateChangeListener> listeners = new ArrayList<WorkflowRequestStateChangeListener>(); synchronized void addListener(WorkflowRequestStateChangeListener listener) < listeners.add(listener); >synchronized void removeListener(WorkflowRequestStateChangeListener listener) < listeners.remove(listener); >>

Listing 3. Event source class

public class WorkflowRequestStateChangeListenerStandardImpl implements WorkflowRequestStateChangeListener < public void handleEvent(ApproveRequestEvent event) < WorkflowRequest request = (WorkflowRequest)event.getSource(); . >>

Listing 4. Event listener implementation class

public class WorkflowFacade < private WorkflowRequestStateChangeListener listener; public WorkflowFacade(WorkflowRequestStateChangeListener listener) < this.listener = listener; >public void save(WorkflowRequest request) < //save workflow request in database . //fire event to request approval listener.handleEvent(new ApproveRequestEvent(request)); >>

Listing 5. Code that fires event

WorkflowFacade facade = new WorkflowFacade(new WorkflowStateChangeListenerStandardImpl()); WorkflowRequest request = new WorkflowRequest(); //register listener to the source request.addListener(listener); facade.save(request);

Listing 6. Code to assign event listener implementation instance and register event listener to event source

Using custom events than simply calling methods has an advantage. The code to add and remove event listener on the event source is simple. The event listener can be added or removed in the code outside the event handling code. The event listener implementation or in other words the event handling code can be changed on the fly. An off-the-shelf component can also be used to define the event handler logic if it implements appropriate event listener interface.

Writing such a code with custom events appears more logical than calling methods. However, custom events can increase the code complexity. Hence it is recommended to use them only when they are needed.

Источник

How To Create Your Own Events In Java

I’m pretty new to the Java language. A couple of years ago I started looking into it then pursued PHP as my main focus, so I never really bit into the Java scene. I now am able to focus on learning Java and I am learning a lot.

So here is something I have learned:

Creating custom objects with their own custom events.

When I learned how to do this (thanks to this helpful article: http://www.javaworld.com/javaworld/javaqa/2002-03/01-qa-0315-happyevent.html ), I was very excited. I must have looked like a complete idiot when I shouted for joy in the office and then had to explain my trimuph to all who would hear. My poor wife even got to listen to the story. I’ve spared my children.

I’ll give a brief overview of what I learned from that article. It is from 2002, but I found it very helpful, so check it out if you can.

Four things you need:

The event class will extend java.util.EventObject like this:

public class MyEventClass extends java.util.EventObject < //here's the constructor public MyEventClass(Object source) < super(source); >>

The interface will look something like this:

public interface MyEventClassListener

The event source will look something like this:

public class MyEventSource < private List _listeners = new ArrayList(); public synchronized void addEventListener(MyEventClassListener listener) < _listeners.add(listener); >public synchronized void removeEventListener(MyEventClassListener listener) < _listeners.remove(listener); >// call this method whenever you want to notify //the event listeners of the particular event private synchronized void fireEvent() < MyEventClass event = new MyEventClass(this); Iterator i = _listeners.iterator(); while(i.hasNext()) < ((MyEventClassListener) i.next()).handleMyEventClassEvent(event); >> >

The event listener will look something like this:

public class MyEventListener implements MyEventClassListener < // . code here //implement the required method(s) of the interface public void handleMyEventClassEvent(EventObject e) < // handle the event any way you see fit >>

You’ll need to register the MyEventListener object with the MyEventSource object by call its addEventListener method.

So that’s it in a nutshell; not too bad. I think I may create a more usable and complete example.

Share this:

Like this:

37 thoughts on “ How To Create Your Own Events In Java ”

Hey, i just have to create the interface to deal with my specific event, my event class and i have to advise in one class where the event is going to fire right?

Basically the class that is going to publish the event (broadcast it) to the listeners (subscribers) maintains a list of these listeners; these listeners implement a specific interface or abstraction that the publisher knows about; and whenever the publisher wants to notify these subscribers, it does so by iterating through them; for instance if my publisher is a GUI form and I have a logic that runs when the button is pushed, then the class that has the logic will subscribe to that particular button push event. Hope that helps.

This should be part of the main article. It really put the peices together in human terms and made sense of the code. Being new to java from the .Net world and having to hit the ground running at a sr dev level there are a great many things i know can be done but have to find the correct way to do. This being a notable example. That said this article is by far the best example / tutorial ive seen on the topic.

Источник

Оцените статью