Why a EDT violation happens?

烈酒焚心 提交于 2019-12-13 12:23:01

问题


I started to use CheckThreadViolationRepaintManager to detect EDT violations.

It complains about:

partner = getParameter("partner",generatePartnerSelectionPanel(),Design.partnerSelectionDuration);

Because it does not like generatePartnerSelectionPanel() because it does not like JPanel panel = new JPanel(); in this method. But I cannot find out why there should be a problem around that.

In more details, generatePartnerSelectionPanel() generates a JPanel (I do it not in the EDT) but then, in the getParameter I add the JPanel to the main JFrame and I do it in the EDT (using invokeLater).

So, why there should be a problem?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/2727841/why-a-edt-violation-happens

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