SWT/Swing -> Threads n' Hell

I have an SWT application. I was frustrated at SWT for not making it easy to do what I wanted to do. So I used Swing. Swing made my life easy. Yay. Except now, the two have to talk. The issue is, they are running on different threads, and whenever I try to run an SWT GUI method from Swing, I get:

Exception in thread "AWT-EventQueue-0" org.eclipse.swt.SWTException: Invalid thread access

Oh joy. So, how do I fix this? If this was Objective-C, I could use:

- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait

But it's not, so I can't. Is there no way to run method A on thread B? When that thread is existing?


I haven't worked much with SWT but it seems that SWT will striclty prohibit accessing an SWT object in the non UI thread. You can queue up a request to talk to an object on the SWT.

This link explains this better

The example suggests you to use syncExec

display.syncExec( new Runnable() { public void run(){ label.setText(text); } });

This I can assume will queue up the Runnable on the main SWT UI thread and thus the access would be legal.

Note: I read over the link again, syncExec will end up freezing your Swing EDT. If you invoke syncExec, it will throw the Runnable on the SWT queue and wait for it to be completed. You can look at asyncEvent to throw the runnable on the queue and continue on working.

人吐槽 人点赞



用户名: 密码:
验证码: 匿名发表


查看评论:SWT/Swing -> Threads n' Hell