2014-01-09 64 views
0

我有Java swing应用程序,我想从C#运行它。JNI4NET - 如何从C#类库项目运行Java应用程序?

当我从WindowsFormsApplication使用它时,它可以正常工作(请参阅下面的工作版本)。我将WindowsFormsApplication窗口设置为不可见,并且在我调用Java中的System.exit(0);之后应用程序退出。但是当我尝试使用ClassLibrary项目运行相同的程序时,我无法调用Application.Run();,因此程序立即退出。 (在使用断点的调试模式中,我可以看到使用GUI的Java程序正确初始化并开始运行)。如何让它等到Java程序退出?

使用WindowsFormsApplication工作例如:

using System; 
using System.IO; 
using System.Collections.Generic; 
using System.Linq; 
using System.Windows.Forms; 

using java.io; 
using java.lang; 
using java.util; 
using net.sf.jni4net; 
using net.sf.jni4net.adaptors; 

using tt_factory; 

namespace BookMap 
{ 
    static class Program 
    { 
     /// <summary> 
     /// The main entry point for the application. 
     /// </summary> 
     [STAThread] 
     static void Main(string [] args) 
     { 
      Init(); 
      TT_Factory.create_replay(); // creates Java GUI 
      Application.Run(); 
     } 

     private static void Init() 
     { 
      BridgeSetup bridgeSetup = new BridgeSetup(true); 
      bridgeSetup.AddJVMOption("-Xms900m"); 
      bridgeSetup.AddAllJarsClassPath(Application.StartupPath + "\\..\\lib"); 
      bridgeSetup.JavaHome = Application.StartupPath + "\\..\\jre"; 
      Bridge.CreateJVM(bridgeSetup); 
      Bridge.RegisterAssembly(typeof(TT_Factory).Assembly); 
     } 
    } 
} 

例使用ClassLibrary项目,ConsoleApplication作为测试

namespace Test 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      BookMap.create_replay(); 
      /***** This method is implemented by ClassLibrary project: 
      public static void create_replay() 
      { 
       init_jvm(); 
       TT_Factory.create_replay(); 
      } 
      ***** How to make program to wait here ? *****/ 
     } 
    } 
} 

更新:

我试图开始新的线程,但结果是一样的:程序立即退出。

namespace Test 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Thread thread = new Thread(new ThreadStart(BookMap.create_replay)); 
      thread.Start(); 
      thread.Join(); 
     } 
    } 
} 
+0

你能解释一下为什么你想调用一个不能保证在用户上下文中运行的交互式程序吗? –

+0

我有一个完整的GUI应用程序,用Java swing编写。现在我想让它可以从C#访问,因为应用程序所需的一些数据源只有C#API。但它已经在WindowsFormsApplication中运行良好。我只是不能使用ClassLibrary项目来运行它。 – Serg

+0

为了清楚起见,我们重新说明我的问题:您有一个应用程序,希望在基于用户的上下文中运行(某人登录到计算机上并将查看您期望显示的漂亮UI) - 您想从一个不知道向客户展示用户界面的任何代码 - 为什么你会认为这是件好事?是的,这是可能的(相当简单),但很少,如果有的话,是有道理的。您尚未描述您希望所述应用程序运行的环境,因此很难猜测它发生的原因 - 只知道这是一个坏主意。 –

回答

0

这是一个简单的解决方案。我还不知道如何,但程序等待,直到Java应用程序调用System.exit(0),然后退出,无论Console.Read();

MSDNRead方法在输入字符时阻止其返回;当您按下Enter键时它会终止。

在这种情况下,没有人按下控制台中的输入。

namespace Test 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      BookMap.create_replay(); 
      Console.Read(); 
     } 
    } 
} 
相关问题