4

I found tons of posts about handling events of existing java classes, but nothing about creating a class with events from scratch.
What is the translation to java of this vb.net snippet?

Public Class TestClass
    Event TestEvent()
    Sub TestFunction()
        RaiseEvent TestEvent()
    End Sub
End Class
Public Class Form1
    Dim WithEvents TC As New TestClass
    Sub OnTestEvent() Handles TC.TestEvent
    End Sub
End Class

Thanks.

A--C
  • 36,351
  • 10
  • 106
  • 92
stenci
  • 8,290
  • 14
  • 64
  • 104

1 Answers1

3

Here's a good link on the "theory" behind the Java event model:

And here's a link illustrating how to create your own, custom events:

And here's a really good example from SO:

// REFERENCE: https://stackoverflow.com/questions/6270132/create-a-custom-event-in-java
import java.util.*;

interface HelloListener {
    public void someoneSaidHello();
}


class Initiater {
    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();
    }
}


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();
    }
}

The key is:

1) create an "interface" that defines your "event" (such as the events in the AWT event model)

2) create a class that "implements" this event (analogous to "callbacks" in languages like C - and effectively what VB does for you automagically with the "Event" type).

'Hope that helps ... at least a little bit!

Community
  • 1
  • 1
paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • 1
    I just want to add, that event handling is generally solved using the Observer design pattern. @paulsm4 provided you one example of that. If you search on google "observer pattern" you will find lots of literature about that. Here is one more example: http://searchdaily.net/observer-pattern-java-example/ – tuga Jan 01 '13 at 23:59
  • @Paulo Silva - you're absolutely correct. And in fact the example above was explicitly written as an example of [Observer Pattern](http://en.wikipedia.org/wiki/Observer_pattern) – paulsm4 Jan 02 '13 at 00:03
  • Thanks, it helps, but after looking at your answer I have another question: Is it possible to create two different listeners for two instances of the same class? Something like: `Sub Obj1OnEvent() Hndles Obj.Event Sub Obj2OnEvent() Hndles Obj.Event` – stenci Jan 03 '13 at 05:30