Subscribing to events
Subscribe to any .NET event with Javonet. Event subscription works the same way as listening Java events. The performance of event subscription is extremely high and allows you to interact with .NET code like it was native Java code. When the event occurs, your Java listener callback is called in a separate thread.
The simplest way to subscribe an event is to use an anonymous Java class.
Assuming we have a custom .NET Framework DLL with the following class inside:
namespace TestNamespace
{
public delegate void EventExampleHandler(object sender, string e);
public class EventExample
{
public event EventExampleHandler SampleEvent;
public void EventInvoke()
{
if (SampleEvent != null)
SampleEvent(this, "Called from .NET!");
}
}
}
The anonymous class should implement special INEventListener interface to subscribe to .NET event.
// Todo: activate Javonet and add reference to .NET library
NObject sampleObj = Javonet.New("TestNamespace.EventExample");
sampleObj.addEventListener("SampleEvent", new INEventListener() {
public void eventOccurred(Object[] arguments) {
System.out.println(arguments[1]);
}
});
sampleObj.invoke("EventInvoke");
Using .NET standard library elements
To create a .NET button and listen for a "Click" event:
// Todo: activate Javonet
Javonet.addReference("System.Windows.Forms.dll");
NObject button = Javonet.New("System.Windows.Forms.Button");
button.set("Text", "Click me!");
button.addEventListener("Click", new INEventListener() {
public void eventOccurred(Object[] arguments) {
System.out.println(".NET event occurred");
}
});
The anonymous class should implement special INEventListener interface. Alternatively you can write a separate class as the event listener by extending NEventListener and overriding the eventOccurred method, or by implementing the ((INEventListener)) interface.
package utils;
import com.javonet.api.INEventListener;
//Your custom Java listener class for .NET events
public class MyEventListener implements INEventListener {
@Override
public void eventOccurred(Object[] arguments) {
System.out.println(".NET Event Occurred");
}
}
Usage of your listener class:
// Todo: activate Javonet
Javonet.addReference("System.Windows.Forms.dll");
NObject button = Javonet.New("System.Windows.Forms.Button");
button.set("Text", "Click me!");
MyEventListener listener = new MyEventListener();
button.addEventListener("Click", listener);
Was this article helpful?