我正在使用 SWT 开发一个 java 应用程序。我已经使用 JNativeHook 库实现了 HotKeyFunction。它全局监听热键,即当应用程序未处于焦点时。按下热键时,我必须使应用程序处于焦点状态。所以我尝试使用 shell.setFocus() 、 shell.forceFocus() 。但是我收到“无效线程访问”异常。查看文档,它显示
Throws:
SWTException - ERROR_WIDGET_DISPOSED - if the receiver has been disposed ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
对于这两个函数。我知道 JNativeHook 使用另一个线程来监听键,我试图从该线程调用这些方法,但 shell 是使用主线程创建的。现在我如何从主线程。我对线程的了解非常少。
PS:我没有在任何地方显式创建任何线程。
最佳答案
您需要使用Display.asyncExec
或Display.syncExec
方法。您可以使用 Display.getDefault 获取 Display 实例,或者从 UI 对象获取它并将其传递给您的线程。
// do something on the UI thread asynchronously
Display.getDefault().asyncExec(new Runnable() {
public void run() {
// access to UI
}
});
// do something on the UI thread synchronously
Display.getDefault().syncExec(new Runnable() {
public void run() {
// access to UI
}
});
关于java - 如何解决java中的无效线程访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25479914/