Subscribing to events

You are browsing legacy Javonet 1.5 (Java<>.NET bridge for Windows) documentation. Use the left side menu or click here to switch to latest Javonet 2.0 documentation. Javonet 2.0 allows you to use any module from JVM, CLR, Netcore, Python, Ruby, Perl, NodeJS on Windows, Linux and MacOs from any application created in Java, Clojure, Groovy, Kotlin, C#, F#, J#, VB.NET, Python, Perl, Ruby, JavaScript, TypeScript, C++ and GoLang

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.

I code in:
// 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:

I code in:
// 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.

I code in:
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:

I code in:
// 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);

See Live Example!