Click here to Skip to main content
13,898,182 members
Click here to Skip to main content
Add your own
alternative version


39 bookmarked
Posted 24 Jan 2006
Licenced CPOL

Example of using Object-Oriented Java Native Interface in C++

, 3 Feb 2006
Rate this:
Please Sign up or sign in to vote.
Demonstrates an easy way of creating and embedding Java objects into C++ code, with Object-Oriented JNI.


As I am a lazy boy in writing code, I try to develop tools for reducing my efforts in programming. This article is a result of using the last tool developed by me.


Java Native Interface (JNI) is a set of low level C functions that are very complex to use. A great number of things should be written to support JNI code integrity. Using pure JNI looks like developing OLE modules in MS Visual C++ without using ATL tools and libraries. I have found dozens of products that partially solve this problem, but they all have some serious defects, like:

  • complexity, user should spend a lot of time learning them;
  • unfriendly to use, after generating code, user has to manually modify the project for compiling and execution;
  • huge overhead, many standard modules should be included in the user's code;
  • commercial restrictions, the products are very expensive and assume royalties;
  • huge size of the generated code.

By developing the Object-Oriented JNI (OOJNI) SDK, I tried to solve the problems mentioned above. OOJNI completely hides the low level JNI specifics, making C++ programming with JNI simple and comfortable. This SDK preserves the Java style programming in C++.

Object-Oriented JNI demo project

Before you can compile and run the sample project, please make sure that you have properly installed the Java Development Kit (JDK) version 1.3.x or higher on your computer.

The code of this application was generated with MS Visual Studio and OOJNI Advanced Add-in for VC 6.0. Java class wrappers were created using the runtime library (rt.jar) of IBM JDK 1.3. To run this code, put the EXE and the OOJNI runtime (OOJNI.DLL) modules in the same directory.

The code

1. Creating the EmbeddedAWTFrame demo

The application code was generated with the MFC Application Wizard. EmbeddedAWTFrame Demo starts a dialog as the main window.

2. Generating C++ code for gluing Java objects to the demo

To use the Java objects from C++ code, I have generated C++ JNI wrappers with OOJNI Advanced Add-in for VC 6.0. Each C++ JNI class wraps specific Java class members that are used in my code (this option is supported by the tool):

Java class usedC++ wrapper generatedMembers wrapped
java.awt.ButtonCPP_Java_Bridge::java:: awt::ButtonJNIProxyconstructor:
  method: <BR>void setLabel (java.lang.String s);
java.awt.ColorCPP_Java_Bridge::java:: awt::ColorJNIProxyfield:
java.awt.Color blue;
java.awt.PanelCPP_Java_Bridge::java:: awt::PanelJNIProxyconstuctor:
java.awt.Component add(java.awt.Component c);
void setBackground(java.awt.Color c);
javax.swing. SwingUtilitiesCPP_Java_Bridge::javax:: swing::SwingUtilitiesJNIProxymethod:
static void invokeLater(java.lang.Runnable r); WEmbeddedFrameCPP_Java_Bridge::sun::awt:: windows::WEmbeddedFrameJNIProxyconstructor: WEmbeddedFrame(int n);
java.awt.Component add(java.awt.Component c);
void setBounds(int x, int y, int w, int h);
void show();

Each C++ wrapper does all the routine job hidden from the programmer. Look at the wrapper for the method setLabel from CPP_Java_Bridge::java::awt::ButtonJNIProxy:

void CPP_Java_Bridge::java::awt::ButtonJNIProxy::
        setLabel(::jni_helpers::JStringHelper p0) 
        if(setLabel_ID == 0) 
            setLabel_ID = ::jni_helpers::JNIEnvHelper::
                GetMethodID(clazz, "setLabel", 
                                setLabel_ID, (jobject)p0); 
    }catch(::jni_helpers::JVMException e){ 
        throw ::jni_helpers::JVMException(jni_helpers::
           ButtonJNIProxy::setLabel:\n") + 
        throw ::jni_helpers::JVMException("CPP_Java_Bridge" 
            "setLabel: System Error"); 

This code gets the method ID and calls setLabel. It also makes all the C++ - to - Java conversions, and catches Java and C++ exceptions.

In the demo code, I also use a callback interface java.lang.Runnable (it has only one method void run()). For this interface, I generated its C++ implementation (with the tool above):

namespace CPP_Java_Bridge{
    namespace java{ 
        namespace lang{ 
#ifdef __JNIHDLL 
            class __declspec(dllexport) 
              public jni_helpers::JNIInterface{ 
#elif __USEDLL 
            class __declspec(dllimport) 
              public jni_helpers::JNIInterface{ 
            class RunnableJNIImpl: 
              public jni_helpers::JNIInterface{ 
                static const JNINativeMethod methods[]; 
                static const jbyte bytes[]; 
                static const char* _clazzName; 
                virtual void run(){} 
namespace RunnableJNIImpl_Native{ extern "C" { 
    JNIEXPORT void JNICALL run(JNIEnv *, 
                        jobject, jlong); 

The method void run() is virtual, empty, and should be overloaded for use:

class Runnable: public 
    CPP_Java_Bridge::java::lang::RunnableJNIImpl { 
             windows::WEmbeddedFrameJNIProxy& frm; 
    CPP_Java_Bridge::java::awt::ButtonJNIProxy& button1; 
    CPP_Java_Bridge::java::awt::ButtonJNIProxy& button2; 
    CPP_Java_Bridge::java::awt::PanelJNIProxy& panel; 
    CRect rc; 
               windows::WEmbeddedFrameJNIProxy& embFrm, 
        CPP_Java_Bridge::java::awt::ButtonJNIProxy& b1, 
        CPP_Java_Bridge::java::awt::ButtonJNIProxy& b2, 
        CPP_Java_Bridge::java::awt::PanelJNIProxy& p): 
        ,panel(p) { } 
    void init(HWND hwnd, CRect& rc) { 
               WEmbeddedFrameJNIProxy tmp((long)hwnd); 
        frm = JObject_t(tmp); 
        this->rc = rc; 
    void run(); 

3. Put it all together

The application starts a dialog as the main window, with Java components embedded in it. To compile the code, I added this line to the EmbeddedAWTFrameDlg.h file:

#include "defproxies.h"

It includes all the referenced OOJNI headers. For activating the Java engine in the CEmbeddedAWTFrameApp::InitInstance() function, I call jni_helpers::JVM::load(). This method loads the default JVM installed on your computer:

BOOL CEmbeddedAWTFrameApp::InitInstance() 
    // Standard initialization 
    // If you are not using these features
    // and wish to reduce the size 
    // of your final executable,
    // you should remove from the following 
    // the specific initialization
    // routines you do not need. 

#ifdef _AFXDLL Enable3dControls(); 
    // Call this when using MFC in a shared DLL 
#else Enable3dControlsStatic(); 
    // Call this when linking to MFC statically 

    CEmbeddedAWTFrameDlg dlg; 
    m_pMainWnd = &dlg; 
    int nResponse = dlg.DoModal(); 
    if (nResponse == IDOK) 
        // TODO: Place code here
        // to handle when the dialog is 
        // dismissed with OK 
    } else if (nResponse == IDCANCEL) 
        // TODO: Place code here
        // to handle when the dialog is 
        // dismissed with Cancel

    // Since the dialog has been closed,
    // return FALSE so that we exit the 
    // application, rather than start
    // the application's message pump. 
    return FALSE; 

The dialog's constructor creates the Java GUI objects, and constructs the Runnable object with the GUI objects created:

CEmbeddedAWTFrameDlg::CEmbeddedAWTFrameDlg(CWnd* pParent /*=NULL*/) 
    : CDialog(CEmbeddedAWTFrameDlg::IDD, pParent) 
    ,run(embFrm, button1, button2, panel) 
    // NOTE: the ClassWizard will
    // add member initialization here 
    // Note that LoadIcon does not require
    // a subsequent DestroyIcon in Win32 
    m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); 

On the dialog's WM_SHOWWINDOW event, the Java GUI objects are embedded to the dialog. For demonstrating the usage of the Java callback interface in C++, I do this embedding asynchronously (by calling javax.swing.SwingUtilities.invokeLater with the run object):

void CEmbeddedAWTFrameDlg::OnShowWindow(BOOL bShow, UINT nStatus) 
    CDialog::OnShowWindow(bShow, nStatus); 
        CRect rc; 
        CRect rcDlgRc; 
        CRect rcDlgCl; 
        run.init(m_hWnd, rc); 

The JVM calls the Runnable::run() function from EventQueue, and here I do the main things:

void Runnable::run() { 
    HWND h = (HWND)jni_helpers::JNIEnvHelper::
    ::MoveWindow(h, rc.left,, 
      rc.right - rc.left, rc.bottom -, TRUE);
    button1.setLabel("Java Button1");
    button2.setLabel("Java Button2");

This function gets the WEmbeddedFrame object's window handle to resize it, fills the Panel object with two push buttons, sets its background color to blue, and inserts the Panel to the WEmbeddedFrame object, which is shown.

Embedding SWING components

You can modify the example to embed SWING components into JNI code. But because of a bug in WEmbeddedFrame class SWING components will not respond to key/mouse events. Having been created WEmbeddedFrame object has no LightweightDispatcher associated with it. This dispatcher should redirect events to lightweight components inside the heavyweight container. The dispatcher should be created explicitly in JNI code just after constructing WEmbeddedFrame object. Do this in the function Runnable::init():

void init(HWND hwnd, CRect& rc) {
            WEmbeddedFrameJNIProxy tmp((long)hwnd); 

    // Create LightweightDispatcher object to enable 
    // lightweight component in WEmbeddedFrame. We use
    // java::awt::ContainerJNIProxy to access its private
    // member field 'dispatcher'
    java::awt::ContainerJNIProxy c(tmp);
    c.dispatcher = 

      frm = JObject_t(tmp); 
      this->rc = rc; 

The wrappers java::awt::ContainerJNIProxy and java::awt::LightweightDispatcherJNIProxy are generated with OOJNI Tool for classes java.awt.Container and java.awt.LightweightDispatcher.

Other resources

  • IBM, SUN JDK1.3.x and higher
  • OOJNI Advanced Add-in Demo for VC 6.0 is available here.


I would like to express my deep gratitude to my friend Igor Ladnik for giving me remarks of material significance.


  • 18/01/2006 - Initial version.
  • 31/01/2006 - Updated.


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


About the Author

Vitaly Shelest
Software Developer (Senior) Javain Ltd
Israel Israel
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralSee also Pin
SilentSilent25-Jan-06 22:34
memberSilentSilent25-Jan-06 22:34 
GeneralRe: See also Pin
vitallis26-Jan-06 0:45
membervitallis26-Jan-06 0:45 
GeneralNewJNI Pin
domKing7-Feb-06 17:12
memberdomKing7-Feb-06 17:12 
Generalremove this add Pin
srsr25-Jan-06 3:28
membersrsr25-Jan-06 3:28 
GeneralRe: remove this add Pin
vitallis25-Jan-06 5:07
membervitallis25-Jan-06 5:07 
QuestionOOJNI License?? Pin
Roland Pibinger24-Jan-06 9:43
memberRoland Pibinger24-Jan-06 9:43 
AnswerRe: OOJNI License?? Pin
vitallis24-Jan-06 23:11
membervitallis24-Jan-06 23:11 
GeneralRe: OOJNI License?? Pin
vektuz3-Feb-06 13:45
membervektuz3-Feb-06 13:45 
GeneralRe: OOJNI License?? Pin
Vitaly Shelest4-Feb-06 20:29
memberVitaly Shelest4-Feb-06 20:29 
GeneralRe: OOJNI License?? Pin
Vitaly Shelest5-Feb-06 1:28
memberVitaly Shelest5-Feb-06 1:28 

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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190306.1 | Last Updated 3 Feb 2006
Article Copyright 2006 by Vitaly Shelest
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid