java - Jpype: "Can' t 启动 AWT,因为 Java 是在第一个线程上启动的。”

标签 java jpype

我正在使用 Jpype 将 java 类用于 python 脚本。 java类涉及AWT库的使用:这似乎是问题所在。

这是 python 脚本:

import jpype
import os.path
import threading

jarpath = os.path.join(os.path.abspath('.'), 'build/jar')
target=jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.ext.dirs=%s" % jarpath)
Capture = jpype.JClass('Capture')            # Capture is the class, contained in ./ folder
t = Capture(50,354,90,90,130,650,"num",36);  # create the instance
jpype.shutdownJVM()

所以我只是想实例化这个类,然后退出。 这是 java 类。我只报告导致错误的代码:

class Capture {

    public Capture(int x, int y, int width, int height, int mouseNextX, int mouseNextY, final String fnamestart, final int countmax) {
            //...
            images = new ArrayList<BufferedImage>();
            getImages(fnamestart,countmax);  //THIS is the problem
}

    // reference to getImages() method:
    public void getImages(String fname, int countmax) {

        images.clear();
        for(int i=0; i<=countmax; i++) {
            try {
                BufferedImage img = ImageIO.read(new File(fname+i+".bmp")); 
                images.add(img);
            } catch(IOException e) {
                images.add(null);
            }
         }
    }
}

此代码在运行 python 脚本时会引发以下错误:

 jpype._jexception.VirtualMachineErrorPyRaisable: java.lang.InternalError: Can't start
 the AWT because Java was started on the first thread.  Make sure StartOnFirstThread is
 not specified in your application's Info.plist or on the command line

长话短说,这是一个已知问题:Eclipse 有“它自己的版本”,然后就解决了。不幸的是,没有人谈到这个与 jpype 相关的问题。

我尝试了这些解决方案,但没有用:

  • 在 python 脚本中,在启动 JVM 之前启动一个线程。然后在另一个线程中启动 JVM。

  • 在 python 脚本中,使用参数 -XstartOnFirstThread 启动 JVM:

    target=jpype.startJVM(jpype.getDefaultJVMPath(), "-XStartOnFirstThread -Djava.ext.dirs=%s" % jarpath)
    
  • 在 java 代码中:使用 AWT 方法 invokeLater,在构造函数中:

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            images = new ArrayList<BufferedImage>();
            getImages(fnamestart,countmax);
        }
    });
    

我真的不知道该怎么办,希望你能帮助我。 谢谢,

乔瓦尼

最佳答案

使用这个参数:

jpype.startJVM(jpype.getDefaultJVMPath(), '-Djava.awt.headless=true')

关于java - Jpype: "Can' t 启动 AWT,因为 Java 是在第一个线程上启动的。”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11374211/

相关文章:

java - Jsoup在Java中解析动态加载网页

java - 使用对象列表,如何访问对象属性并打印它们?

python - JPype 的 properties access shadows 方法用属性名

java - DFC 中的原始 SQL (Documentum)

java - 使用 Spring JPA 为 STRING_AGG 和 Postgresql 为 Group_By 设置聚合函数

Java - WHILE 中的 Swing 计时器,带有启用/禁用按钮

java - 未找到 JPype 类

java - 从 Java 调用 python 函数的不同/更好的方法

java - Jpype导入在jar中找不到模块

python-2.7 - 如何防止 ctypes.CDLL ("jvm.dll") 在 Windows Server 2016 上出现 "module not found"错误?