gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:12:57 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com