Why a EDT violation happens?

半腔热情 提交于 2019-12-04 18:33:35

An EDT violation doesn't mean something necessarily did go wrong, it means you tried to do a GUI related action on a thread other than the EDT (a situation where something might go wrong).

Creating a new Swing component is covered by "doing something GUI related", hence the warning about the violation.

This forum has quite a discussion on why it's not recommended to create Swing components on other threads.

Bill K

Usually this will happen if you create any GUI components in the thread handed to you in main.

Now, in reality nothing bad will ever happen as long as you don't modify it after you've realized it (setVisible(true) or pack() will realize a frame), BUT Sun found some edge case that they claim make it so this can cause a problem.

So to be perfectly correct have your main construct your first window inside an invokeLater or invokeAndWait.

Actually, I wonder if exiting your main thread right after the invokeLater might allow your entire app to exit (since the window almost certainly hasn't had time to come up yet)... You might want to use invokeAndWait unless your main thread doesn't exit.

Swing is thread-hostile. Even if a component is not realised, it may still access shared resources or call EventQueue.invokeLater. There was a period when it was widely stated that Swing components could be created off the, but that was incorrect.

In addition to using the CheckThreadViolationRepaintManager I've been using an Aspect Oriented solution to detect when any Swing components are constructed off of the EDT. This is an elegant way to troubleshooting EDT violations if you use AspectJ.

See this blog post for details:

Debugging Swing, the final summary

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