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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With