0

I am developing a java app using SWT.I have implemented HotKeyFunction using the JNativeHook Library.It listens for hotkeys globally i.e when the app is not in focus also.I have to bring the app in focus when the hotkeys are pressed.so i tried to use shell.setFocus() , shell.forceFocus().But i get an "Invalid Thread Access" exception.Looking at the documentation ,it shows

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

for both the functions.I understand that JNativeHook uses one more thread to listen for the keys and i am trying to call these methods from that thread but the shell has been created using main thread.Now How do i call these methods from the main Thread.I have very minimal knowledge in threads.

PS: I have not created any threads explicitly anywhere.

Community
  • 1
  • 1
user3873909
  • 191
  • 1
  • 3
  • 15

1 Answers1

2

You need to use the Display.asyncExec or Display.syncExec methods. You can obatin the Display instance with Display.getDefault or get it from an UI object and pass it to your thread.

   // 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
      }
   }); 
MatF
  • 1,728
  • 2
  • 14
  • 31