问题
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.
回答1:
Here's a good link on the "theory" behind the Java event model:
- http://docs.oracle.com/javase/1.4.2/docs/guide/awt/1.3/designspec/events.html
And here's a link illustrating how to create your own, custom events:
- http://castever.wordpress.com/2008/07/31/how-to-create-your-own-events-in-java/
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!
来源:https://stackoverflow.com/questions/14115289/event-handling-in-java-for-a-vb-net-expert