Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a custom event in Java

I want to do something like this in Java but I don't know the way:

When event "object 1 say 'hello'" happens, then object 2 responds to that event by saying "hello".

Can somebody give me a hint or sample code?

like image 669
conmadoi Avatar asked Jun 07 '11 18:06

conmadoi


People also ask

Can we create custom events?

Creating a Custom Event: To create a custom event we use the Event constructor or CustomEvent interface. The Event constructor creates an Event and CustomEvent creates an Event with more functionality. The below steps are followed in order to create one using a new Event. We create an event using the Event constructor.

What is an example of an event in Java?

An event is a signal received by a program from the operating system as a result of some action taken by the user, or because something else has happened. Here are some examples: The user clicks a mouse button. The user presses a key on the keyboard.


1 Answers

You probably want to look into the observer pattern.

Here's some sample code to get yourself started:

import java.util.*;  // An interface to be implemented by everyone interested in "Hello" events interface HelloListener {     void someoneSaidHello(); }  // Someone who says "Hello" class Initiater {     private List<HelloListener> listeners = new ArrayList<HelloListener>();      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...");     } }  class Test {     public static void main(String[] args) {         Initiater initiater = new Initiater();         Responder responder = new Responder();          initiater.addListener(responder);          initiater.sayHello();  // Prints "Hello!!!" and "Hello there..."     } } 

Related article: Java: Creating a custom event

like image 147
aioobe Avatar answered Sep 28 '22 09:09

aioobe