obs
obs

Reputation: 21

show hello world swing with jni

This is my main.cpp code:

#include <jni.h>
#include <QDebug>
int main(int argc, char *argv[]) {
    JavaVM *jvm;
    JNIEnv *env;
    jstring jstr;
    jobjectArray args;
    jclass stringClass;

    JavaVMInitArgs vm_args;
    JavaVMOption options[3];

    options[0].optionString = "-Djava.compiler=NONE";
    options[1].optionString = "-Djava.classpath=.";
    options[2].optionString = "";

    vm_args.version = JNI_VERSION_1_6;
    vm_args.nOptions = 3;
    vm_args.options = options;
    vm_args.ignoreUnrecognized = JNI_TRUE;

    jint res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
    if (res < 0) {
        qDebug()<<"Can't create Java VM\n";
        exit(1);
    };
    jclass cls = env->FindClass("HelloWorldSwing");
    if (cls == 0) qDebug()<<"Sorry, I can't find the class";
    jmethodID get_main_id =
    env->GetStaticMethodID(cls,"main","([Ljava/lang/String;)V");

    jstr=env->NewStringUTF("hola que tal");
    stringClass=env->FindClass("java/lang/String");
    args=env->NewObjectArray(1,stringClass,jstr);

    env->CallStaticVoidMethod(cls,get_main_id,args);

    jvm->DestroyJavaVM();
    qDebug()<<"Java VM destroy\n";

}//end main.

HelloWorldSwing is a class that show a jframe with "Hello world" text, but don't show nothing, if i write system.out.println("hello world")in the java class, function correctly.

Upvotes: 2

Views: 588

Answers (2)

obs
obs

Reputation: 21

The problem was in the main class of java. JNI calls the main method and when this end, the program end. I just put a guithread.join (); in the main method and all run correctly.

Upvotes: 0

technomage
technomage

Reputation: 10069

You're destroying the VM before it has a chance to display the UI.

The call to System.out.println is synchronous, so it happens before you destroy the VM.

Creating a UI involves creating and dispatching events on a separate thread. If you were to simply pause for several seconds before destroying the VM, I think you'd see your UI show up.

Upvotes: 1

Related Questions