如何在 Java 按钮 (Swing/GUI) 单击上运行 python 代码



我在Python中创建了一个程序,该程序可以打开网络摄像头并实时识别相机帧中的人脸。我觉得从我的 IDE 运行 python 代码看起来很不完美。我想在用户单击我的 Java GUI 表单中的按钮时执行 python 代码。

提前感谢!阿什温

执行此操作的一种肮脏的黑客方法是调用Runtime.exec("python command here")并将侦听器附加到由此创建的进程。本文介绍了与此技术相关的方法:https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html 。一个粗略的例子如下所示:

button.setOnAction(event -> {
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec("python command");
    process.getOutputStream()  // add handling code here
});

但是,请考虑这是否是您真正想要做的事情。为什么不在Python中创建用户界面。流行的GTK GUI库具有Python绑定(文档在 https://python-gtk-3-tutorial.readthedocs.io/en/latest/(。

或者考虑用 Java 编写人脸识别组件。如果你纯粹从头开始编写它,这可能很困难,但如果使用像OpenCV这样的库,可能有可用的Java绑定。

一般来说,如果没有特别的小心,跨语言交流是困难的,而且非常容易出错,所以要仔细考虑你是否需要这种确切的设置。

我认为

您可以使用

    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec(path + "XXX.py");

裁判:https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html

并等待 py 完成输出 JSON 格式,最后使用Java雷丁JSON数据处理你想做。

老实说,我想上面给出的答案是正确的。只需在按钮事件中使用另一个线程,这样您的 Java 程序主线程就不必等到事情完成,并且可以防止 UI 冻结。

创建线程

public class MyRunnable implements Runnable {
           private String commandParameters = "";
           // Just Creating a Constructor 
           public MyRunnable(String cmd)
           {
                this.commandParameters = cmd;
           }
           public void run()
           {
             try
             {
               Runtime runtime = Runtime.getRuntime();
               // Custom command parameters can be passed through the constructor.
               Process process = runtime.exec("python " + commandParameters);
               process.getOutputStream();
             }
             catch(Exception e)
             {
                    // Some exception to be caught..
             }
           }   
}

并在您的按钮事件中执行此操作

yourBtn.setOnAction(event -> {
   try{
     Thread thread = new Thread(new MyRunnable("command parameter string"));
     thread.start();
   }
   catch(Exception e)
   {
           // Some Expection..
   }
});

现在您的主线程不会冻结或等待命令执行完成。希望这能解决问题。如果你想将一些变量值传递给"python命令",只需在创建MyRunnable Class时让你成为一个构造函数,并将其作为参数传递给MyRunnable Class的构造函数

现在,当您单击按钮时,这将运行一个新线程。这不会弄乱您的主 UI 线程。

最新更新