Guice creates Swing components outside of UI thread problem?

霸气de小男生 提交于 2019-11-30 22:20:27

IMO you should not create components using Guice but services which in turn will create your components. Once you have you service injected it should be easy to make sure that component creation happens on EDT (using invokeAndWait )

You might want to check out my Guts-GUI project (Swing app framework built upon Guice). Guts-GUI makes sure your components, even when created by Guice, are created in the EDT.

Guice itself doesn't provided any way, out of the box, to declare a component to be created in the EDT. I am not sure if Guice Scopes could be used for that (I think yes), however, I am not sure that any Scope-based solution would be worthwhile, in particular regarding performance.

The first step to solving this problem is to make sure that Guice Injector is created from inside the EDT (by using SwingUtilities.invokeAndWait or invokeLater). This is what Guts-GUI does in the first place. Hence, if some components are created early by Guice, they will be created in the EDT.

Then you must ensure that any instances injected by Guice, and that require creation of injected Swing components, are obtained (eg through Injector.getInstance(...)) from the EDT.

In fact, Swing is not multi-threaded and requires to be run in EDT. As a consequence, yes, your components should be prepared in EDT by calling invokeAndWait.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!