您的位置:首页 > 编程语言 > Java开发

org.eclipse.swt.SWTException: Invalid thread access解法

2012-09-14 20:47 465 查看
我们有一个应用:swing写的客户端软件,其中有个email button的写邮件操作。在实现整个功能之后,我测试了很多遍都没有出现什么问题。但是我的一位同事,在连续的拷贝,粘贴,删除,保存,email之后,出现了如下的error:

[2012-09-13 16:32:15,351] FATAL [AWT-EventQueue-0] (post_mail:SelectedSizingResultPanel.java:345)  : - error 

org.eclipse.swt.SWTException: Invalid thread access

at org.eclipse.swt.SWT.error(SWT.java:3884)

at org.eclipse.swt.SWT.error(SWT.java:3799)

at org.eclipse.swt.SWT.error(SWT.java:3770)

at org.eclipse.swt.widgets.Widget.error(Widget.java:463)

at org.eclipse.swt.widgets.Shell.<init>(Shell.java:282)

at org.eclipse.swt.widgets.Shell.<init>(Shell.java:273)

at org.eclipse.swt.widgets.Shell.<init>(Shell.java:223)

at view.SendEmail.execute(SendEmail.java:26)

        ......

因为我重现不了,这个情况,强烈要求同事重新操作,重现这个error,可是不管后来怎么操作,都无法再现。

于是我只好根据上面的log,和具体的代码来查找原因。

错误出现在shell这个地方,但是shell的代码是这样子写的。

Display display = Display.getCurrent();
Shell shell = new Shell(display);


 所以我强烈怀疑是display的问题。

于是我google是Display.getCurrent()。找到如下的描述说得到一个Display实例有两种方法,其一就是:Display.getCurrent() 

http://wiki.eclipse.org/FAQ_How_do_I_get_a_Display_instance%3F 写道

A display is forever tied to the thread that created it, and a thread can have only one active display; a display is active until it is disposed of
 

大致是说:一个显示界面和创建它的线程永久的联系在一起,并且一个线程只能拥有一个可用的显示界面;这个显示界面在显示期间一直有效。
If you call Display.getCurrent, it returns the display that was created in that thread, if any. Here is an example:

public static Display getDisplay() {
Display display = Display.getCurrent();
//may be null if outside the UI thread
if (display == null)
display = Display.getDefault();
return display;
}
 

之后我查了:Display.getCurrent()和Display.getDefault()的区别

philips 写道

Display.getCurrent() 当当前代码和当前的界面(UI)线程在同一个线程时,将返回当前的Display对象。反之,当不在同一个线程时,则返回null。

Display.getDefault() 显然,针对线程使用。将返回最近的一个UI线程的Display对象。
 

于是我严重怀疑是我同事在连续操作的时候,导致Display.getCurrent()得到了一个null值,然后Shell shell = new Shell(display);的时候,出错了。我应该只要加上判null的代码就可以了关于Display.getCurrent()和Display.getDefault()参考
http://jarg.iteye.com/blog/840214
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐