Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C#
Article

Java/.NET Integration as Simple as Possible

Rate me:
Please Sign up or sign in to vote.
4.62/5 (10 votes)
5 Jul 2006CPOL3 min read 160.1K   2.3K   39   43
Describes the simplest way to embed .NET controls into a Java GUI (without using COM or any other technology).

Sample Image

Introduction

For a number of years, I have been developing software for integrating applications written in different platforms. And in my business, I face with interoperability issues: Java and C++, Java and COM, Java and .NET. To solve them, I have developed a number of tools. The last one is the Object-Oriented JNI for .NET (low-level). This is an SDK that wraps the standard Java Native Interface for C++ in .NET classes. Playing with this tool, I have made direct embedding of .NET controls into a Java GUI.

What is Object-Oriented JNI for .NET?

The main idea of Object-Oriented JNI (OOJNI) for .NET is to expose the standard Java Native Interface SDK to .NET programmers as a set of classes. For this, I wrapped all JNI reference types, like jobject, jstring, jclass, etc., with classes:

  • JObject wraps the jobject reference,
  • JString keeps the jstring reference and makes all default string conversions Java/.NET and .NET/Java,
  • JWeakReference wraps the jweak type,
  • JClass for the jclass reference,
  • Java array classes for all primitive Java types and objects. These classes support easy access to Java array items, and can handle and create multi-dimensional Java arrays.

Most standard JNI functions are represented in a managed class ObjectOrientedJNI.JNINativeMethod as static methods. This SDK is compatible with JNI for JDK 1.3.x. The OOJNI SDK also includes a number of useful helpers for easy JNI coding in .NET. All SDK is packed into one module: OOJNIDOTNET.DLL. It is loaded first in a Java process, with the System.load(...) or the System.loadLibrary(...) methods.

An example of direct embedding of .NET contols into a Java GUI

1. Writing Java code for OOJNI

The class MainFrame creates a SWING Frame Window with the FrameWindow object, which is used as a container for the .NET UserControl object and JButton which closes the application. To activate OOJNI in Java, the application loads the module OOJNIDOTNET.DLL first, then the other JNI modules can be loaded (.NET module CSharpInJava.DLL).

Java
import java.awt.BorderLayout;
import java.awt.Color; 
import javax.swing.JButton; 
import javax.swing.JFrame;
 

public class MainFrame extends JFrame { 
    static{ 
        System.loadLibrary("oojnidotnet"); 
        System.loadLibrary("CSharpInJava"); 
    }
 
    FrameWindow canvas; 
    JButton okButton; 
    public MainFrame() { 
        super("qwerty"); 
        initialize(); 
    } 
    public void initialize(){ 
        okButton = new JButton(); 
        okButton.setText("Close"); 
        getContentPane().setLayout(new BorderLayout()); 
        getContentPane().add(canvas = 
               new FrameWindow(), BorderLayout.CENTER); 
        getContentPane().add(okButton, BorderLayout.SOUTH); 
        canvas.setBackground(Color.blue); 
        addWindowListener(new java.awt.event.WindowAdapter() { 
            public void windowClosing(java.awt.event.WindowEvent evt) { 
                System.exit(0); 
            } 
        }); 
        okButton.addActionListener(new ActionListener(){ 
            public void actionPerformed(ActionEvent arg0) { 
                System.exit(0); 
            } 
        }); 
        pack(); 
        setSize(200, 200); 
    } 
    public static void main(String args[]) { 
        new MainFrame().setVisible(true); 
    } 
}

The Java class FrameWindow is used as a container for the .NET UserControl object:

Java
import java.awt.Canvas;
import java.awt.event.ComponentEvent; 
import java.awt.event.ComponentListener;
 
 
public class FrameWindow extends Canvas { 
    int ref = 0;
      //Called by JVM to create Canvas' Peer 
    public void addNotify() { 
        super.addNotify(); 
        ref = create(); 
    }
     //Called by JVM to destroy Canvas' Peer 
    public void removeNotify() { 
        dispose(ref); 
        super.removeNotify(); 
    }
     //Creates .NET UserControl object and 
     //returns the reference to it 
     native int create();
     //Destroys .NET object by ref value
    native void dispose(int ref); 
}

This class keeps a reference to the .NET container object created and the two native methods implemented in CSharpInJava.DLL:

  • create - creates a .NET UserControl object in FrameWindow on an addNotify call,
  • dispose - destroys .NET objects in FrameWindow on a removeNotify call.

2. Implementing Java native methods in .NET JNI code

Java native methods can be implemented in .NET code in any class and namespace. The only restrictions are:

  • these methods should be static,
  • their names must be the same as generated with the javah.exe tool,
  • all pointer types (like JNIEnv*, jobject, jstring, jweak, jclass, etc.) should be substituted with int.
C#
using System;
using ObjectOrientedJNI; 
using System.Windows.Forms; 
namespace CSharpInJava { 
    public class NativeJavaMethods { 
        // Creates .NET UserControl object in Canvas
        static int Java_FrameWindow_create(int env, int obj) {
        // Check if the current thread was attached to JNI 
        if(!JNIEnvHelper.isInitialized())
            // Attach the current thread              
            JNIEnvHelper.init(env);
            // Create .NET MyEmbeddedFrame in Canvas' Window
             MyEmbeddedFrame embeddedWindow = 
                      new MyEmbeddedFrame(new JObject(obj));
            // Make GlobalReference copy with
            // MyEmbeddedFrame object and
            // return it to Java code.
            GlobalReference gref = 
                  new GlobalReference(embeddedWindow, true );
            return gref.Reference.ToInt32();
        }
        // Destroys .NET Controls embedded
        // in Canvas and .NET GlobalReference
        static void Java_FrameWindow_dispose(int env, int obj, int peer) {
            ((MyEmbeddedFrame)new GlobalReference(peer, 
                              false).Object).Dispose(); 
        }
    }
}

3. MyEmbeddedFrame class design

MyEmbeddedFrame extends the EmbeddedFrame class from OOJNI (see, P.Foot's example), which embeds .NET controls embedded into a Java application. Add to MyEmbeddedFrame a constructor that gets a JObject instance of Canvas:

C#
public MyEmbeddedFrame(JObject obj) : base(o){}

Implement EmbeddedFrame's method addComponents to initialize the .NET GUI:

C#
protected override void addComponents() { 
        InitializeComponent();
}

In the MS Visual Studio Designer, add to MyEmbeddedFrame, Button and Editor controls (it fills the InitializeComponent method with the code you need).

Points of interest

Now having learnt how to embed .NET controls in a Java GUI, try to write code for embedding ActiveX in Java with .NET. But it is not a simple task as above.

Other resources

  • IBM, Sun JDK1.3.x and higher,
  • .NET Framework 1.1,
  • Object-Oriented JNI for .NET (low-level) is available here.

Thanks

Thanks to a friend of mine, Igor Ladnik, for giving me remarks of material significance.

History

  • 05/07/2006 - Initial version.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Javain Ltd
Israel Israel
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionDoesn't work on a 64-bit Java Pin
Member 786161628-Jan-13 8:13
Member 786161628-Jan-13 8:13 
First: This is really awesome and I'm happy you did this.
The only problem is that when I use this with a 64-bit Java (and 64-bit Windows of course), it has a UnsatisfiedLinkError regarding the oojnidotnet.dll. When I use a 32-bit Java installation, it works really good, but I'm worrying if there could be some others who have 64 bit too and want to use my application. I think I need a 64-bit version of the dll.
Here the error message:
Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\****\oojnidotnet.dll: Can't load IA 32-bit .dll on a AMD 64-bit platform

What should I do?
BTW: Thank you for this.
QuestionSend Parameters Question Pin
ali_amiri24-Jun-12 3:34
ali_amiri24-Jun-12 3:34 
QuestionProblem! My dll didn't work! Pin
ali_amiri23-Jun-12 4:11
ali_amiri23-Jun-12 4:11 
AnswerRe: Problem! My dll didn't work! Pin
Vitaly Shelest23-Jun-12 5:46
Vitaly Shelest23-Jun-12 5:46 
GeneralRe: Problem! My dll didn't work! Pin
ali_amiri23-Jun-12 19:01
ali_amiri23-Jun-12 19:01 
GeneralRe: Problem! My dll didn't work! Pin
Vitaly Shelest23-Jun-12 20:43
Vitaly Shelest23-Jun-12 20:43 
QuestionThanks Pin
sanya.fesak21-Sep-11 19:06
sanya.fesak21-Sep-11 19:06 
AnswerRe: Thanks Pin
ali_amiri23-Jun-12 19:03
ali_amiri23-Jun-12 19:03 
NewsPassing Arguments Pin
sikayak11-Apr-10 0:05
sikayak11-Apr-10 0:05 
GeneralRe: Passing Arguments Pin
Vitaly Shelest11-Apr-10 10:06
Vitaly Shelest11-Apr-10 10:06 
GeneralRe: Passing Arguments Pin
sikayak11-Apr-10 22:14
sikayak11-Apr-10 22:14 
GeneralRe: Passing Arguments Pin
ali_amiri24-Jun-12 19:22
ali_amiri24-Jun-12 19:22 
QuestionHow to get a release version Pin
Bruno Rosenberger2-Nov-09 21:21
Bruno Rosenberger2-Nov-09 21:21 
AnswerRe: How to get a release version Pin
Vitaly Shelest3-Nov-09 7:25
Vitaly Shelest3-Nov-09 7:25 
Generaljni4net [modified] Pin
Zamboch31-Oct-09 10:35
Zamboch31-Oct-09 10:35 
GeneralRe: jni4net [modified] Pin
Vitaly Shelest1-Nov-09 1:38
Vitaly Shelest1-Nov-09 1:38 
GeneralRe: jni4net Pin
Zamboch4-Nov-09 7:55
Zamboch4-Nov-09 7:55 
GeneralRe: jni4net Pin
binhvtt30-Dec-10 22:35
binhvtt30-Dec-10 22:35 
QuestionHow about WPF? Pin
RKaderli8-Sep-08 1:20
RKaderli8-Sep-08 1:20 
AnswerRe: How about WPF? Pin
vsha8-Sep-08 2:00
vsha8-Sep-08 2:00 
QuestionRe: How about WPF? Pin
RKaderli8-Sep-08 3:27
RKaderli8-Sep-08 3:27 
AnswerRe: How about WPF? Pin
Vitaly Shelest4-May-09 5:25
Vitaly Shelest4-May-09 5:25 
QuestionGood work:) Pin
rajangarg12320-Aug-08 20:11
rajangarg12320-Aug-08 20:11 
AnswerRe: Good work:) Pin
vsha2-Sep-08 20:51
vsha2-Sep-08 20:51 
GeneralJava/.NET Integration Pin
eatwo27-May-08 1:06
eatwo27-May-08 1:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.