Embedding Java Applets in .NET Applications


Embedding Java Applets in .NET Applications by Matt Loar

As a part of my Computing Habitat Programming Competition entry, I wanted to add a live video feed from the Siebel Center Webcam. However, my application was written in C#, and the only interface with the webcam was a Java applet. I could have used the Microsoft WebBrowser ActiveX Control; however, the WebBrowser control was slow and even buggier than Internet Explorer itself. I needed a way to directly interface with the Java applet.

Luckily, Microsoft included a utility with Visual Studio called JBIMP, which converts the Java bytecodes in a JAR file to MSIL bytecodes, creating a .NET assembly DLL. Its usage is simple:

jbimp /t:library OurApplet.jar

Simply add a reference to this DLL to your C#, J#, or VB.NET application, and you can access the Java component's interface as easily as if you were writing your application in Java.

To display the applet, however, takes a little more work. Unfortunately, it is not currently possible to place a Java applet directly on a Windows Form. Instead, we must use the Visual J# runtime library, vjslib, to create an AWT Frame (Swing will be implemented in VJ# 2005). After creating the frame and adding our control to it, we need to derive classes from java.applet.AppletStub and java.applet.AppletContext to pass parameters to our applet.

The initialization ends up like this:

java.awt.Frame frm = new java.awt.Frame("Look, Ma! Java!");

// just make the form have one big box for components
frm.setLayout(new java.awt.GridLayout(1,0));
frm.show();

JavaPackage.OurApplet appl = new JavaPackage.OurApplet();
frm.add(appl);
/* JavaStub is our subclass of AppletStub that passes any necessary parameters */
appl.setStub(new JavaStub());
appl.init();
// this next call is necessary to make the applet appear
frm.validate();
appl.start();

That's it! By using a few Native Windows API calls, you can even make your applet appear as part of your C# form.