![](/img/trans.png)
[英]How to identify java swing button in a GUI application and click on that button using another Java code in eclipse?
[英]How do I run a python code on Java Button (Swing/GUI) click?
我用 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 rading 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 类时创建一个构造函数,并将其作为参数传递给 MyRunnable 类的构造函数。
现在,当您单击按钮时,这将运行一个新线程。 这不会弄乱您的主 UI 线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.